Last active
November 16, 2023 07:39
-
-
Save seki/610a42932a85209aaa33547ae983bbdf to your computer and use it in GitHub Desktop.
capture
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
% ruby capture.rb
X 2023-08-27 12:30:02 +0900 1.0 3.14