Skip to content

Instantly share code, notes, and snippets.

@rmg
Last active December 25, 2015 17:49
Show Gist options
  • Save rmg/7015828 to your computer and use it in GitHub Desktop.
Save rmg/7015828 to your computer and use it in GitHub Desktop.
Example of how to use ERB and DATA in Ruby. Handy combination.
require 'ostruct'
require 'erb'
class RenderableFile
def self.get_data(name = nil)
unless const_defined?(:DATA)
const_set(:DATA, File.open( __FILE__ ).read.split( /^__END__\n/, 2 ).last)
end
if name
DATA.split( /^#{name}\n/, 2 ).last
end
end
TEMPLATE = get_data(:__ERB__)
def erb
@erb ||= ERB.new(TEMPLATE, nil, '-')
end
def erb_binding
list = ["it can do this", "it's in stdlib"]
OpenStruct.new(list: list).instance_eval { binding }
end
def render
erb.result(erb_binding)
end
end
__END__
# Yay ERB!
__ERB__
# Generated by XXXX. Do not edit.
<% list.each do |item| %>
ERB is awesome because: <%= item %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment