Skip to content

Instantly share code, notes, and snippets.

@thbar
Created January 30, 2010 12:55
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save thbar/290538 to your computer and use it in GitHub Desktop.
require 'erb'
data = { :version => RUBY_PLATFORM }
class Hash
def method_missing(method,*args)
if (keys.include?(method) && args.empty?)
self[method]
else
super
end
end
end
x = 42
template = ERB.new <<-EOF
The value of x is: <%= version %>
EOF
puts template.result(data.send(:binding))
~$ irb
irb(main):001:0> require 'erb'
=> true
irb(main):002:0> data = { :version => RUBY_PLATFORM }
=> {:version=>"i686-darwin10.0.0"}
irb(main):003:0> class Hash
irb(main):004:1> def method_missing(method,*args)
irb(main):005:2> if (keys.include?(method) && args.empty?)
irb(main):006:3> self[method]
irb(main):007:3> else
irb(main):008:3* super
irb(main):009:3> end
irb(main):010:2> end
irb(main):011:1> end
=> nil
irb(main):012:0> x = 42
=> 42
irb(main):013:0> template = ERB.new <<-EOF
irb(main):014:0" The value of x is: <%= version %>
irb(main):015:0" EOF
=> #<ERB:0x101689b90 @filename=nil, @src="_erbout = ''; _erbout.concat \"The value of x is: \"; _erbout.concat(( version ).to_s); _erbout.concat \"\\n\"\n; _erbout", @safe_level=nil>
irb(main):016:0> puts template.result(data.send(:binding))
The value of x is: i686-darwin10.0.0
=> nil
irb(main):001:0> require 'erb'
=> true
irb(main):002:0> data = { :version => RUBY_PLATFORM }
=> {:version=>"i386-mswin32"}
irb(main):003:0> class Hash
irb(main):004:1> def method_missing(method,*args)
irb(main):005:2> if (keys.include?(method) && args.empty?)
irb(main):006:3> self[method]
irb(main):007:3> else
irb(main):008:3* super
irb(main):009:3> end
irb(main):010:2> end
irb(main):011:1> end
=> nil
irb(main):012:0> x = 42
=> 42
irb(main):013:0> template = ERB.new <<-EOF
irb(main):014:0" The value of x is: <%= version %>
irb(main):015:0" EOF
=> #<ERB:0x37a2bc0 @safe_level=nil, @src="_erbout = ''; _erbout.concat \"The value of x is: \"; _erbout.concat(( version
).to_s); _erbout.concat \"\\n\"\n_erbout", @filename=nil>
irb(main):016:0> puts template.result(data.send(:binding))
The value of x is: i386-mswin32
=> nil
# more work on this - now I'm able to rely on Hash-based data in ERB
require 'erb'
require 'ostruct'
class OpenStruct
# monkey patch to ensure we'll get the right bindings
# required only on IronRuby/JRuby
def get_our_own_binding
binding
end
end
class Templator
def self.render(template,values)
template = ERB.new(template)
context = OpenStruct.new(values)
template.result(context.get_our_own_binding)
end
end
template = <<-EOF
The value of x is: <%= version %>
EOF
puts Templator.render(template, { :version => RUBY_PLATFORM })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment