ERB 클래스
ERB 클래스
ERB 클래스 (이름은 Embedded Ruby의 줄임말이에요)는 쓰기 쉬우면서도 꽤 강력한 템플릿 처리기예요. 텍스트 안에 Ruby 코드 조각을 끼워 넣고, 실행 결과로 바꿔 주는 방식이죠.
사용 준비
ERB를 쓰려면 먼저 require를 해야 해요 (이 페이지의 예시들은 이미 require된 상태를 전제해요):
require 'erb'
간단히 보는 동작 방식
ERB가 어떻게 동작하는지 한 눈에 보면:
- *템플릿(template)*을 만들 수 있어요: 특별한 형식의 태그가 포함된 평문 문자열이에요.
- 템플릿을 저장할 ERB 객체를 만들 수 있어요.
- 인스턴스 메서드
ERB#result를 호출해서 *결과(result)*를 얻을 수 있어요.
ERB는 세 종류의 태그를 지원해요:
-
표현식 태그(Expression tag):
<%=로 시작해서%>로 끝나요. Ruby 표현식을 담고 있고, 결과에서 표현식의 값이 태그 전체를 대체해요.template = 'The magic word is <%= magic_word %>.' erb = ERB.new(template) magic_word = 'xyzzy' erb.result(binding) # => "The magic word is xyzzy."위
result호출은binding인자를 넘겨요. 이 binding에 변수magic_word가 문자열 값'xyzzy'에 묶여 있어요. 아래 호출은 binding을 넘길 필요가 없는데, 그 표현식Date::DAYNAMES가 전역적으로 정의돼 있기 때문이에요:ERB.new('Today is <%= Date::DAYNAMES[Date.today.wday] %>.').result # => "Today is Monday." -
실행 태그(Execution tag):
<%로 시작해서%>로 끝나요. 실행할 Ruby 코드를 담고 있어요.template = '<% File.write("t.txt", "Some stuff.") %>' ERB.new(template).result File.read('t.txt') # => "Some stuff." -
주석 태그(Comment tag):
<%#로 시작해서%>로 끝나요. 주석 텍스트를 담고 있고, 결과에서 태그 전체가 생략돼요.template = 'Some stuff;<%# Note to self: figure out what the stuff is. %> more stuff.' ERB.new(template).result # => "Some stuff; more stuff."
간단한 예시
ERB가 실제로 움직이는 간단한 예시를 볼게요:
template = 'The time is <%= Time.now %>.'
erb = ERB.new(template)
erb.result
# => "The time is 2025-09-09 10:49:26 -0500."
여기서 일어나는 일을 정리하면:
- 평문 문자열이 변수
template에 담겨요. 그 안의 표현식 태그'<%= Time.now %>'에는 Ruby 표현식Time.now가 들어 있어요. - 그 문자열이 새 ERB 객체에 들어가 변수
erb에 저장돼요. erb.result호출이, 호출 시점에 계산된Time.now의 런타임 값을 담은 문자열을 만들어 줘요.
ERB 객체는 재사용할 수 있어요:
erb.result
# => "The time is 2025-09-09 10:49:33 -0500."
또 다른 예시:
template = 'The magic word is <%= magic_word %>.'
erb = ERB.new(template)
magic_word = 'abracadabra'
erb.result(binding)
# => "The magic word is abracadabra."
정리하면:
- 평문 문자열이 변수
template에 담겨요. 그 안의 표현식 태그'<%= magic_word %>'는 변수 이름magic_word를 갖고 있어요. - ERB 객체를 만들 때
magic_word가 정의돼 있을 필요는 없어요. magic_word = 'abracadabra'로 변수에 값을 할당해요.erb.result(binding)호출이magic_word의 값을 담은 문자열을 만들어 줘요.
역시 ERB 객체는 재사용할 수 있어요:
magic_word = 'xyzzy'
erb.result(binding)
# => "The magic word is xyzzy."
바인딩(Bindings)
결과 문자열을 만들어 주는 result 메서드 호출은 Binding 객체를 인자로 요구해요. 그 binding 객체가 표현식 태그의 표현식들을 위한 바인딩을 제공하죠.
필요한 binding을 제공하는 방법은 세 가지예요:
- 기본 binding(Default binding)
- 로컬 binding(Local binding)
- 확장 binding(Augmented binding)
기본 Binding
result 메서드에 binding 인자를 넘기지 않으면 기본 binding을 써요: new_toplevel 메서드가 돌려주는 것이죠. 이 binding은 Ruby 자체가 정의한, 즉 Ruby의 상수와 변수에 대한 바인딩을 갖고 있어요.
이 binding은 Ruby의 상수와 변수만 참조하는 표현식 태그라면 충분해요. Ruby의 전역 상수 RUBY_COPYRIGHT와 전역 변수 $0만 참조하는 예시예요:
template = <<TEMPLATE
The Ruby copyright is <%= RUBY_COPYRIGHT.inspect %>.
The current process is <%= $0 %>.
TEMPLATE
puts ERB.new(template).result
The Ruby copyright is "ruby - Copyright (C) 1993-2025 Yukihiro Matsumoto".
The current process is irb.
(현재 프로세스가 irb인 건 우리가 irb에서 예시를 실행하고 있기 때문이에요!)
로컬 Binding
기본 binding은 그곳에 정의되지 않은 상수나 변수를 참조하는 표현식에는 충분하지 않아요:
Foo = 1 # Defines local constant Foo.
foo = 2 # Defines local variable foo.
template = <<TEMPLATE
The current value of constant Foo is <%= Foo %>.
The current value of variable foo is <%= foo %>.
The Ruby copyright is <%= RUBY_COPYRIGHT.inspect %>.
The current process is <%= $0 %>.
TEMPLATE
erb = ERB.new(template)
아래 호출은 Foo와 foo가 로컬에 정의돼 있지만 기본 binding에는 없으므로 NameError를 던져요:
erb.result # Raises NameError.
로컬로 정의된 상수와 변수를 쓸 수 있게 하려면, result를 로컬 binding과 함께 호출하면 돼요:
puts erb.result(binding)
The current value of constant Foo is 1.
The current value of variable foo is 2.
The Ruby copyright is "ruby - Copyright (C) 1993-2025 Yukihiro Matsumoto".
The current process is irb.
확장 Binding
변수 바인딩(상수 바인딩은 아님)을 제공하는 또 다른 방법은 result_with_hash(hash)를 쓰는 거예요. 넘긴 해시는 기본 binding의 복사본 안에서 변수를 정의하고 할당하는 데 쓰이는 이름/값 쌍을 가져요:
template = <<TEMPLATE
The current value of variable bar is <%= bar %>.
The current value of variable baz is <%= baz %>.
The Ruby copyright is <%= RUBY_COPYRIGHT.inspect %>.
The current process is <%= $0 %>.
TEMPLATE
erb = ERB.new(template)
bar와 baz가 기본 binding에도 로컬 binding에도 없으므로, 다음 두 호출은 모두 NameError를 던져요:
puts erb.result # Raises NameError.
puts erb.result(binding) # Raises NameError.
아래 호출은 bar와 baz가 (new_toplevel에서 파생된) 새 binding 안에서 정의되도록 하는 해시를 넘겨요:
hash = {bar: 3, baz: 4}
puts erb.result_with_hash(hash)
The current value of variable bar is 3.
The current value of variable baz is 4.
The Ruby copyright is "ruby - Copyright (C) 1993-2025 Yukihiro Matsumoto".
The current process is irb.
태그(Tags)
위 예시들은 표현식 태그를 썼어요. ERB에서 쓸 수 있는 태그들은 이렇게 정리할 수 있어요:
- 표현식 태그: Ruby 표현식을 담고, 결과에서 태그 전체가 표현식의 런타임 값으로 대체돼요.
- 실행 태그: Ruby 코드를 담고, 결과에서 태그 전체가 코드의 런타임 값으로 대체돼요.
- 주석 태그: 주석 코드를 담고, 결과에서 태그 전체가 생략돼요.
표현식 태그
표현식 태그로 템플릿에 Ruby 표현식을 임베드할 수 있어요.
문법은 <%= expression %>인데, expression은 유효한 Ruby 표현식이면 뭐든 돼요.
result 메서드를 호출하면 그 표현식을 평가하고 태그 전체를 표현식의 값으로 대체해요:
ERB.new('Today is <%= Date::DAYNAMES[Date.today.wday] %>.').result
# => "Today is Monday."
ERB.new('Tomorrow will be <%= Date::DAYNAMES[Date.today.wday + 1] %>.').result
# => "Tomorrow will be Tuesday."
ERB.new('Yesterday was <%= Date::DAYNAMES[Date.today.wday - 1] %>.').result
# => "Yesterday was Sunday."
표현식 앞뒤의 공백은 허용되지만 필수는 아니고, 그런 공백은 결과에서 제거돼요.
ERB.new('My appointment is on <%=Date::DAYNAMES[Date.today.wday + 2]%>.').result
# => "My appointment is on Wednesday."
ERB.new('My appointment is on <%= Date::DAYNAMES[Date.today.wday + 2] %>.').result
# => "My appointment is on Wednesday."
실행 태그
실행 태그로 템플릿에 Ruby 실행 코드를 임베드할 수 있어요.
문법은 <% code %>인데, code는 유효한 Ruby 코드면 뭐든 돼요.
result 메서드를 호출하면 코드를 실행하고 실행 태그 전체를 제거해요 (결과에는 텍스트를 만들지 않아요):
ERB.new('foo <% Dir.chdir(Dir.pwd) %> bar').result # => "foo bar"
임베드된 코드 앞뒤의 공백은 선택이에요:
ERB.new('foo <%Dir.chdir(Dir.pwd)%> bar').result # => "foo bar"
실행 태그와 텍스트를 번갈아 쓰면 조건문, 반복문, case 문 같은 제어 구조를 만들 수 있어요.
조건문:
template = <<TEMPLATE
<% if verbosity %>
An error has occurred.
<% else %>
Oops!
<% end %>
TEMPLATE
erb = ERB.new(template)
verbosity = true
erb.result(binding)
# => "\nAn error has occurred.\n\n"
verbosity = false
erb.result(binding)
# => "\nOops!\n\n"
섞인 텍스트 안에 표현식 태그가 또 있을 수도 있어요.
반복문:
template = <<TEMPLATE
<% Date::ABBR_DAYNAMES.each do |dayname| %>
<%= dayname %>
<% end %>
TEMPLATE
ERB.new(template).result
# => "\nSun\n\nMon\n\nTue\n\nWed\n\nThu\n\nFri\n\nSat\n\n"
제어가 아닌 다른 Ruby 코드 줄을 텍스트와 섞을 수도 있고, Ruby 코드 안에 일반 Ruby 주석도 넣을 수 있어요:
template = <<TEMPLATE
<% 3.times do %>
<%= Time.now %>
<% sleep(1) # Let's make the times different. %>
<% end %>
TEMPLATE
ERB.new(template).result
# => "\n2025-09-09 11:36:02 -0500\n\n\n2025-09-09 11:36:03 -0500\n\n\n2025-09-09 11:36:04 -0500\n\n\n"
실행 태그는 여러 줄의 코드도 담을 수 있어요:
template = <<TEMPLATE
<%
(0..2).each do |i|
(0..2).each do |j|
%>
* <%=i%>,<%=j%>
<%
end
end
%>
TEMPLATE
ERB.new(template).result
# => "\n* 0,0\n\n* 0,1\n\n* 0,2\n\n* 1,0\n\n* 1,1\n\n* 1,2\n\n* 2,0\n\n* 2,1\n\n* 2,2\n\n"
실행 태그의 약식(Shorthand) 형식
키워드 인자 trim_mode: '%'를 주면 실행 태그의 약식 형식을 쓸 수 있어요. 아래 예시는 <% code %> 대신 약식 % code를 써요:
template = <<TEMPLATE
% priorities.each do |priority|
* <%= priority %>
% end
TEMPLATE
erb = ERB.new(template, trim_mode: '%')
priorities = [ 'Run Ruby Quiz',
'Document Modules',
'Answer Questions on Ruby Talk' ]
puts erb.result(binding)
* Run Ruby Quiz
* Document Modules
* Answer Questions on Ruby Talk
약식 형식에서는 '%' 문자가 코드 줄의 첫 번째 문자여야 해요 (앞 공백 없음).
원치 않는 빈 줄 제거하기
trim_mode를 주지 않으면 모든 빈 줄이 결과에 들어가요:
template = <<TEMPLATE
<% if true %>
<%= RUBY_VERSION %>
<% end %>
TEMPLATE
ERB.new(template).result.lines.each {|line| puts line.inspect }
"\n"
"3.4.5\n"
"\n"
trim_mode: '-'를 주면 소스 줄이 -%>(대신 %>)로 끝나는 각 빈 줄을 제거할 수 있어요:
template = <<TEMPLATE
<% if true -%>
<%= RUBY_VERSION %>
<% end -%>
TEMPLATE
ERB.new(template, trim_mode: '-').result.lines.each {|line| puts line.inspect }
"3.4.5\n"
trim_mode: '-' 없이 뒤에 붙은 '-%>' 표기를 쓰면 오류예요:
ERB.new(template).result.lines.each {|line| puts line.inspect } # Raises SyntaxError.
원치 않는 줄바꿈 제거하기
이 템플릿을 생각해 보죠:
template = <<TEMPLATE
<% RUBY_VERSION %>
<%= RUBY_VERSION %>
foo <% RUBY_VERSION %>
foo <%= RUBY_VERSION %>
TEMPLATE
trim_mode를 주지 않으면 모든 줄바꿈이 결과에 들어가요:
ERB.new(template).result.lines.each {|line| puts line.inspect }
"\n"
"3.4.5\n"
"foo \n"
"foo 3.4.5\n"
trim_mode: '>'를 주면 (시작과 무관하게) '%>'로 끝나는 각 줄의 뒤따르는 줄바꿈을 제거할 수 있어요:
ERB.new(template, trim_mode: '>').result.lines.each {|line| puts line.inspect }
"3.4.5foo foo 3.4.5"
trim_mode: '<>'를 주면 '<%'로 시작하고 '%>'로 끝나는 각 줄의 뒤따르는 줄바꿈을 제거할 수 있어요:
ERB.new(template, trim_mode: '<>').result.lines.each {|line| puts line.inspect }
"3.4.5foo \n"
"foo 3.4.5\n"
트림 모드 결합
몇몇 트림 모드는 결합할 수 있어요:
'%-': 약식을 활성화하고'-%>'로 끝나는 각 빈 줄을 생략해요.'%>': 약식을 활성화하고'%>'로 끝나는 각 줄의 줄바꿈을 생략해요.'%<>': 약식을 활성화하고'<%'로 시작하고'%>'로 끝나는 각 줄의 줄바꿈을 생략해요.
주석 태그
주석 태그로 템플릿에 주석을 임베드할 수 있어요. 문법은 <%# text %>인데, text가 주석의 텍스트예요.
result 메서드를 호출하면 주석 태그 전체를 제거해요 (결과에는 텍스트를 만들지 않아요).
예시:
template = 'Some stuff;<%# Note to self: figure out what the stuff is. %> more stuff.'
ERB.new(template).result # => "Some stuff; more stuff."
주석 태그는 템플릿 어디든 나타날 수 있어요.
태그의 시작이 '<% #'가 아니라 반드시 '<%#'여야 해요.
이 예시에서 태그는 '<% #'로 시작하기 때문에 주석 태그가 아니라 실행 태그예요. 그 안의 코드는 통째로 Ruby 스타일 주석이라서 (물론 무시되죠):
ERB.new('Some stuff;<% # Note to self: figure out what the stuff is. %> more stuff.').result
# => "Some stuff;"
인코딩(Encodings)
ERB 객체는 인코딩을 갖고 있어요. 기본적으로 템플릿 문자열의 인코딩이고, 결과 문자열도 그 인코딩을 가져요.
template = <<TEMPLATE
<%# Comment. %>
TEMPLATE
erb = ERB.new(template)
template.encoding # => #<Encoding:UTF-8>
erb.encoding # => #<Encoding:UTF-8>
erb.result.encoding # => #<Encoding:UTF-8>
주어진 템플릿 맨 위에 매직 코멘트를 추가하면 다른 인코딩을 지정할 수 있어요:
template = <<TEMPLATE
<%#-*- coding: Big5 -*-%>
<%# Comment. %>
TEMPLATE
erb = ERB.new(template)
template.encoding # => #<Encoding:UTF-8>
erb.encoding # => #<Encoding:Big5>
erb.result.encoding # => #<Encoding:Big5>
오류 보고(Error Reporting)
(오류를 담은) 이 템플릿을 생각해 보죠:
template = '<%= nosuch %>'
erb = ERB.new(template)
ERB가 오류를 보고할 때는 (가능하면) 파일 이름과 줄 번호를 포함해요. 파일 이름은 filename 메서드에서, 줄 번호는 lineno 메서드에서 와요.
처음에는 각각 nil과 0이에요. 이 초기값들이 각각 '(erb)'와 1로 보고돼요:
erb.filename # => nil
erb.lineno # => 0
erb.result
# => (erb):1:in '<main>': undefined local variable or method 'nosuch' for main (NameError)
filename=과 lineno= 메서드로 여러분 맥락에 더 의미 있는 값을 할당할 수 있어요:
erb.filename = 't.txt'
erb.lineno = 555
erb.result
# => t.txt:556:in '<main>': undefined local variable or method 'nosuch' for main (NameError)
location= 메서드로 두 값을 한꺼번에 설정할 수도 있어요:
erb.location = ['u.txt', 999]
erb.result
# => u.txt:1000:in '<main>': undefined local variable or method 'nosuch' for main (NameError)
평문 텍스트 + 임베드된 Ruby
여기 평문 텍스트 템플릿이 있어요. {% raw %}'%q{ ... }'{% endraw %} 리터럴 표기로 템플릿을 정의하는데 (see %q literals), 이렇게 하면 백슬래시 문제를 피할 수 있어요.
template = %q{
From: James Edward Gray II <[email protected]>
To: <%= to %>
Subject: Addressing Needs
<%= to[/\w+/] %>:
Just wanted to send a quick note assuring that your needs are being
addressed.
I want you to know that my team will keep working on the issues,
especially:
<%# ignore numerous minor requests -- focus on priorities %>
% priorities.each do |priority|
* <%= priority %>
% end
Thanks for your patience.
James Edward Gray II
}
템플릿에는 이것들이 필요해요:
to = 'Community Spokesman <spokesman@ruby_community.org>'
priorities = [ 'Run Ruby Quiz',
'Document Modules',
'Answer Questions on Ruby Talk' ]
마지막으로 ERB 객체를 만들고 결과를 얻어요:
erb = ERB.new(template, trim_mode: '%<>')
puts erb.result(binding)
From: James Edward Gray II <[email protected]>
To: Community Spokesman <spokesman@ruby_community.org>
Subject: Addressing Needs
Community:
Just wanted to send a quick note assuring that your needs are being
addressed.
I want you to know that my team will keep working on the issues,
especially:
* Run Ruby Quiz
* Document Modules
* Answer Questions on Ruby Talk
Thanks for your patience.
James Edward Gray II
HTML + 임베드된 Ruby
이 예시는 HTML 템플릿을 보여줘요.
먼저 커스텀 클래스 Product:
class Product
def initialize(code, name, desc, cost)
@code = code
@name = name
@desc = desc
@cost = cost
@features = []
end
def add_feature(feature)
@features << feature
end
# Support templating of member data.
def get_binding
binding
end
end
아래 템플릿은 이 값들을 필요로 해요:
toy = Product.new('TZ-1002',
'Rubysapien',
"Geek's Best Friend! Responds to Ruby commands...",
999.95)
toy.add_feature('Listens for verbal commands in the Ruby language!')
toy.add_feature('Ignores Perl, Java, and all C variants.')
toy.add_feature('Karate-Chop Action!!!')
toy.add_feature('Matz signature on left leg.')
toy.add_feature('Gem studded eyes... Rubies, of course!')
여기 HTML이에요:
template = <<TEMPLATE
<html>
<head><title>Ruby Toys -- <%= @name %></title></head>
<body>
<h1><%= @name %> (<%= @code %>)</h1>
<p><%= @desc %></p>
<ul>
<% @features.each do |f| %>
<li><b><%= f %></b></li>
<% end %>
</ul>
<p>
<% if @cost < 10 %>
<b>Only <%= @cost %>!!!</b>
<% else %>
Call for a price, today!
<% end %>
</p>
</body>
</html>
TEMPLATE
마지막으로 ERB 객체를 만들고 결과를 얻어요 (빈 줄 일부는 생략):
erb = ERB.new(template)
puts erb.result(toy.get_binding)
<html>
<head><title>Ruby Toys -- Rubysapien</title></head>
<body>
<h1>Rubysapien (TZ-1002)</h1>
<p>Geek's Best Friend! Responds to Ruby commands...</p>
<ul>
<li><b>Listens for verbal commands in the Ruby language!</b></li>
<li><b>Ignores Perl, Java, and all C variants.</b></li>
<li><b>Karate-Chop Action!!!</b></li>
<li><b>Matz signature on left leg.</b></li>
<li><b>Gem studded eyes... Rubies, of course!</b></li>
</ul>
<p>
Call for a price, today!
</p>
</body>
</html>
다른 템플릿 처리기들
여러 Ruby 프로젝트들은 저마다 템플릿 처리기를 갖고 있어요. 예를 들어 Ruby Processing System RDoc도 다른 곳에서 쓸 수 있는 것을 갖고 있죠.
다른 인기 있는 템플릿 처리기는 Ruby Toolbox의 Template Engines 페이지에서 찾을 수 있어요.
상수
VERSION— ERB 버전 문자열.
클래스 메서드
-
new(template, trim_mode: nil, eoutvar: '_erbout')— 주어진 문자열template을 담은 새 ERB 객체를 돌려줘요.키워드 인자
trim_mode: 키워드 인자trim_mode: '%'로 실행 태그의 약식 형식을 쓸 수 있어요. 빈 줄 제어에는'-'(각'%>'로 끝나는 빈 줄 생략)이, 줄바꿈 제어에는'>'(각'%>'로 끝나는 줄의 줄바꿈 생략)와'<>'(각'<%'로 시작하고'%>'로 끝나는 줄의 줄바꿈 생략)이 있어요. 트림 모드는 결합할 수도 있어요.키워드 인자
eoutvar: 키워드 인자eoutvar의 문자열 값은result메서드가 결과 문자열을 만들 때 쓰는 변수의 이름을 지정해요 (src참고). 여러 ERB 템플릿을 같은 binding으로 돌려야 하거나, 출력이 어디로 가는지 제어하고 싶을 때 유용해요. 변수 이름은 밑줄'_'로 시작하는 걸 고르는 게 좋은 관행이에요. -
version → string— ERB 버전 문자열을 돌려줘요.
인스턴스 메서드
-
def_class(super_class = Object, method_name = 'result') → new_class— superclass가super_class이고 인스턴스 메서드method_name을 갖는 새 이름 없는 클래스를 돌려줘요.@arg1과@arg2를 쓰는 표현식 태그가 든 HTML로 템플릿을 만들어요:html = <<TEMPLATE <html> <body> <p><%= @arg1 %></p> <p><%= @arg2 %></p> </body> </html> TEMPLATE template = ERB.new(html)@arg1과@arg2를 갖는 베이스 클래스를 만들어요:class MyBaseClass def initialize(arg1, arg2) @arg1 = arg1 @arg2 = arg2 end enddef_class로:render메서드를 갖는 서브클래스를 만들어요:MySubClass = template.def_class(MyBaseClass, :render)결과를 생성해요:
puts MySubClass.new('foo', 123).render<html> <body> <p>foo</p> <p>123</p> </body> </html> -
def_method(module, method_signature, filename = '(ERB)') → method_name— 주어진 모듈module에 새 인스턴스 메서드를 만들고 그 메서드 이름을 심볼로 돌려줘요. 메서드는 메서드 이름과 (있으면) 인자 이름으로 이뤄진method_signature로 만들어져요.filename은filename의 값을 설정해요 (see Error Reporting).template = '<%= arg1 %> <%= arg2 %>' erb = ERB.new(template) MyModule = Module.new erb.def_method(MyModule, 'render(arg1, arg2)') # => :render class MyClass; include MyModule; end MyClass.new.render('foo', 123) # => "foo 123" -
def_module(method_name = 'erb') → new_module— 인스턴스 메서드method_name을 갖는 새 이름 없는 모듈을 돌려줘요.template = '<%= arg1 %> <%= arg2 %>' erb = ERB.new(template) MyModule = erb.def_module('render(arg1, arg2)') class MyClass include MyModule end MyClass.new.render('foo', 123) # => "foo 123" -
location = [filename, lineno] → [filename, lineno]—filename과, 주어지면lineno의 값을 설정해요 (see Error Reporting). -
make_compiler → erb_compiler— 주어진trim_mode로 새ERB::Compiler를 돌려줘요 (trim_mode값은ERB.new참고):ERB.new('').make_compiler(nil) # => #<ERB::Compiler:0x000001cff9467678 @insert_cmd="print", @percent=false, @post_cmd=[], @pre_cmd=[], @put_cmd="print", @trim_mode=nil> -
result(binding = new_toplevel) → new_string—self에 저장된 템플릿에서 찾은 ERB 태그를 처리해서 만든 문자열 결과를 돌려줘요. 인자 없이 호출하면 기본 binding을 써요 (see Default Binding).binding인자를 주면 로컬 binding을 써요 (see Local Binding).result_with_hash도 함께 보세요. -
result_with_hash(hash) → new_string—self에 저장된 문자열에서 ERB 태그를 처리해서 만든 문자열 결과를 돌려줘요 (see Augmented Binding).result도 함께 보세요. -
run(binding = new_toplevel) → nil—result와 같지만 결과 문자열을 (돌려주는 대신) 출력해요.nil을 돌려줘요. -
set_eoutvar(compiler, eoutvar = '_erbout') → [eoutvar]—ERB::Compiler객체compiler에eoutvar값을 설정하고, 그eoutvar값을 담은 1-요소 배열을 돌려줘요:template = ERB.new('') compiler = template.make_compiler(nil) pp compiler#<ERB::Compiler:0x000001cff8a9aa00 @insert_cmd="print", @percent=false, @post_cmd=[], @pre_cmd=[], @put_cmd="print", @trim_mode=nil>template.set_eoutvar(compiler, '_foo') # => ["_foo"] pp compiler#<ERB::Compiler:0x000001cff8a9aa00 @insert_cmd="_foo.<<", @percent=false, @post_cmd=["_foo"], @pre_cmd=["_foo = +''"], @put_cmd="_foo.<<", @trim_mode=nil>
private 인스턴스 메서드
new_toplevel(symbols) → new_binding—TOPLEVEL_BINDING에 기반한 새 binding을 돌려줘요.result호출의 기본 binding을 만들 때 써요 (see Default Binding). 인자symbols는 심볼 배열인데, 각 심볼symbol이 binding 안에 이미 정의된 같은 이름의 변수가 덮어써지지 않도록 숨기는 새 변수로 정의돼요.