Skip to content

Instantly share code, notes, and snippets.

@seki
Created December 3, 2012 15:32
Show Gist options
  • Save seki/4195735 to your computer and use it in GitHub Desktop.
Save seki/4195735 to your computer and use it in GitHub Desktop.
ERB and block
require 'erb'
class MyERB < ERB
class CompilerWithBlock < ERB::Compiler
def add_put_cmd(out, content)
out.push("#{@put_cmd} #{content_dump(content)}")
end
BLOCK_EXPR = /\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/
def add_insert_cmd(out, content)
if BLOCK_EXPR =~ content
out.push("#{@insert_cmd} #{content}")
else
out.push("#{@insert_cmd}((#{content}).to_s)")
end
end
end
def make_compiler(*args)
CompilerWithBlock.new(*args)
end
def set_eoutvar(compiler, eoutvar = '_erbout')
compiler.put_cmd = "#{eoutvar}.concat"
compiler.insert_cmd = "#{eoutvar} << "
compiler.pre_cmd = ["#{eoutvar} = ''"]
compiler.post_cmd = [eoutvar]
end
end
if __FILE__ == $0
rhtml = <<EOS
<%= (1..10).find_all do |n| %>
<%= n %>
<% n % 2 == 0
end.join %>
EOS
puts MyERB.new(rhtml).src
MyERB.new(rhtml).def_method(Kernel, 'hoge')
puts hoge
end
@seki
Copy link
Author

seki commented Dec 7, 2012

Ruby 2.0のerb.rb

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment