Skip to content

Instantly share code, notes, and snippets.

@seki
Last active November 16, 2023 07:39
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/610a42932a85209aaa33547ae983bbdf to your computer and use it in GitHub Desktop.
Save seki/610a42932a85209aaa33547ae983bbdf to your computer and use it in GitHub Desktop.
capture
require 'erb'
class ERB
class ERBOut
Buffer = String # SafeBuffer if rails
def initialize(s='')
@str = Buffer.new(s)
end
def to_s
@str
end
def <<(other)
@str << other
end
def +(other)
@str << other.to_s
self
end
def capture(*arg, &block)
save = @str
@str = Buffer.new
yield(*arg)
return @str
ensure
@str = save
end
end
def set_eoutvar(compiler, eoutvar = '_erbout')
compiler.put_cmd = "#{eoutvar} << "
compiler.insert_cmd = "#{eoutvar} += " # magic!!
compiler.pre_cmd = ["#{eoutvar} = ERB::ERBOut.new"]
compiler.post_cmd = ["#{eoutvar}.to_s"]
end
class Compiler
def add_insert_cmd(out, content)
out.push("#{@insert_cmd} #{content} ")
end
end
end
if __FILE__ == $0
def capture(*arg, &block)
block.binding.local_variable_get(:_erbout).capture(*arg, &block)
end
def form(*arg, &block)
"<form>" + capture(*arg, &block).upcase + "</form>"
end
include ERB::Util
src =<<RHTML
<%= form 'x' do |it| %>
<foo>
<%=h it %>
</foo>
<%= Time.now %>
<%=h 1.0%>
<%= 3.0 + 0.14 %>
<% end %>
RHTML
erb = ERB.new(src)
# puts erb.src
result = erb.result(binding)
puts result
end
@seki
Copy link
Author

seki commented Aug 27, 2023

% ruby capture.rb

X 2023-08-27 12:30:02 +0900 1.0 3.14

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