Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- def try_require(name, version=nil)
- gem name, version if version
- require name
- rescue LoadError
- if version
- STDERR.puts "Unable to load gem #{name} (#{version})"
- STDERR.puts "to install, type: gem install #{name} -v '#{version}'"
- else
- STDERR.puts "Unable to load gem #{name}"
- STDERR.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(':')
- STDERR.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') { STDERR.puts VERSION; exit 0 }
- slop_opts.on('-h', '--help', 'show help') { STDERR.puts slop_opts; exit 0 }
- opts = Slop::Parser.new(slop_opts).parse(ARGV)
- if opts[:file].nil? && !opts.arguments.empty?
- opts[:file] = Pathname.new File.expand_path(opts.arguments.first)
- end
- if opts.to_hash.values.all?(&:nil?)
- STDERR.puts slop_opts
- exit 1
- end
- if opts[:file].nil?
- STDERR.puts "Missing required option \`file'"
- STDERR.puts slop_opts
- exit 1
- elsif ! opts[:file].exist?
- STDERR.puts "Unable to find file #{opts[:file].to_s}"
- STDERR.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
- STDERR.puts params
- STDOUT.puts test_erb_with_params(opts[:file], params)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement