Skip to content

Instantly share code, notes, and snippets.

@seki
Last active December 22, 2015 09:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seki/6449467 to your computer and use it in GitHub Desktop.
Save seki/6449467 to your computer and use it in GitHub Desktop.
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