dn42-scripts/scripts/utils.rb

58 lines
1.0 KiB
Ruby
Raw Normal View History

2015-01-13 07:19:32 +00:00
require "ostruct"
require "fileutils"
require "erb"
require "json"
require "pathname"
require "pry"
class Registry
PATH = Pathname.new(File.expand_path("../../registry.json", __FILE__))
def initialize
@data = JSON.load(File.open(Registry::PATH))
end
attr_accessor :data
def save
f = File.open(Registry::PATH, "w+")
f.puts JSON.pretty_generate(@data)
f.close
end
end
def atomic_write(path, content)
dir = File.dirname(path)
unless Dir.exist?(dir)
FileUtils.mkdir_p(dir)
end
2015-01-13 07:19:32 +00:00
temp_path = path.to_s + ".tmp"
File.open(temp_path, 'w+') do |f|
f.write(content)
end
FileUtils.mv(temp_path, path)
end
def sh(cmd, *args)
puts "$ #{cmd} "+ args.map {|a| "'#{a}'" }.join(" ")
2015-01-15 07:39:32 +00:00
system(cmd, *args)
2015-01-13 07:19:32 +00:00
end
def die(msg)
$stderr.puts(msg)
exit(1)
end
class TemplateContext < OpenStruct
def get_binding
binding
end
end
class Template
def initialize(path)
@erb = ERB.new(File.read(path), nil, '-')
end
def render(params={})
@erb.result(TemplateContext.new(params).get_binding)
end
end