Last active
December 22, 2015 09:08
-
-
Save seki/6449467 to your computer and use it in GitHub Desktop.
Using BasicObject
This file contains 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
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