Skip to content

Instantly share code, notes, and snippets.

@seki seki/erb_with_hash.rb
Last active Dec 22, 2015

Embed
What would you like to do?
Using BasicObject
module ERBWithHash
class HashAsBinding < BasicObject
def initialize(hash)
@_env = hash
end
def method_missing(msg, *args, &block)
super if block
super unless args.empty?
@_env.fetch(msg) { @_env.fetch(msg.to_s) { super }}
end
end
def result_with_hash(hash)
b = HashAsBinding.new(hash).instance_eval {Kernel.binding}
result(b)
end
end
if __FILE__ == $0
require 'erb'
require 'set'
class ERB
include ERBWithHash
end
my_erb = ERB.new(<<EOS)
file_size: <%= x.read.size%>
collection:
<% z.each_with_index do |it, idx| %> [<%= idx%>] <%= it %>
<% end %>
EOS
puts my_erb.result_with_hash(x: File.open(__FILE__), y: 3, z: ['z', 'zz'])
set = Set.new
set << 'a'
set << 3
set << Thread.current
puts my_erb.result_with_hash(x: File.open(__FILE__), y: nil, z: set)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.