Created
November 5, 2015 15:56
-
-
Save rabbitt/2dd5393fbcc416c52019 to your computer and use it in GitHub Desktop.
Erb file command line tester
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
def try_require(name, version=nil) | |
gem name, version if version | |
require name | |
rescue LoadError | |
if version | |
puts "Unable to load gem #{name} (#{version})" | |
puts "to install, type: gem install #{name} -v '#{version}'" | |
else | |
puts "Unable to load gem #{name}" | |
puts "to install, type: gem install #{name}" | |
end | |
exit 1 | |
end | |
try_require 'slop', '~> 4.2.0' | |
try_require 'awesome_print' | |
try_require 'json' | |
require 'pathname' | |
require 'erb' | |
VERSION = '0.1.0' | |
def test_erb_with_params(erbfile, params = {}) | |
local_binding = binding.clone | |
params.each do |param, value| | |
local_binding.eval("@#{param} = #{value.inspect}") | |
end | |
begin | |
erb = ERB.new(IO.read(erbfile.to_s), nil, '-') | |
erb.filename = erbfile.to_s | |
erb.result(local_binding) | |
rescue StandardError => e | |
file_and_line = e.backtrace.first.split(':')[0..1].join(':') | |
puts "#{file_and_line}: #{e.message}" | |
exit 1 | |
end | |
end | |
module Slop | |
class PathOption < Option | |
def call(value) | |
Pathname.new(value) | |
end | |
end | |
class DictOption < Option | |
def call(value) | |
raise ArgumentError, 'Hash option requires colon delimited key/value pair' unless value.include? ':' | |
@value ||= {} | |
@value.merge(Hash[ [value.split(':', 2)] ]) | |
end | |
end | |
end | |
slop_opts = Slop::Options.new | |
slop_opts.banner = "usage: #{File.basename($0)} [options]" | |
slop_opts.path '-F', '--file', 'file to erbify' | |
slop_opts.dict '-p', '--params', 'colon delimited key:value pair to add as local variables for the erb (use json notation for complex values)' | |
slop_opts.on('-V', '--version', 'show version') { puts VERSION; exit 0 } | |
slop_opts.on('-h', '--help', 'show help') { puts o; exit 0 } | |
opts = Slop::Parser.new(slop_opts).parse(ARGV) | |
if opts.to_hash.values.all?(&:nil?) | |
puts slop_opts | |
exit 1 | |
end | |
if opts[:file].nil? | |
puts "Missing required option \`file'" | |
puts slop_opts | |
exit 1 | |
elsif ! opts[:file].exist? | |
puts "Unable to find file #{opts[:file].to_s}" | |
puts slop_opts | |
exit 1 | |
end | |
params = (opts[:params] || {}).each_with_object({}) do |(key, value), params| | |
params[key] = value =~ /[\{\[]/ ? ( JSON.parse(value) rescue value) : value | |
end | |
puts params | |
puts test_erb_with_params(opts[:file], params) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment