erb 5.0.2 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/erb.rb CHANGED
@@ -12,339 +12,824 @@
12
12
  #
13
13
  # You can redistribute it and/or modify it under the same terms as Ruby.
14
14
 
15
+ # A NOTE ABOUT TERMS:
16
+ #
17
+ # Formerly: The documentation in this file used the term _template_ to refer to an ERB object.
18
+ #
19
+ # Now: The documentation in this file uses the term _template_
20
+ # to refer to the string input to ERB.new.
21
+ #
22
+ # The reason for the change: When documenting the ERB executable erb,
23
+ # we need a term that refers to its string input;
24
+ # _source_ is not a good idea, because ERB#src means something entirely different;
25
+ # the two different sorts of sources would bring confusion.
26
+ #
27
+ # Therefore we use the term _template_ to refer to:
28
+ #
29
+ # - The string input to ERB.new
30
+ # - The string input to executable erb.
31
+ #
32
+
15
33
  require 'erb/version'
16
34
  require 'erb/compiler'
17
35
  require 'erb/def_method'
18
36
  require 'erb/util'
19
37
 
38
+ # :markup: markdown
20
39
  #
21
- # = ERB -- Ruby Templating
40
+ # Class **ERB** (the name stands for **Embedded Ruby**)
41
+ # is an easy-to-use, but also very powerful, [template processor][template processor].
22
42
  #
23
- # == Introduction
43
+ # ## Usage
24
44
  #
25
- # ERB provides an easy to use but powerful templating system for Ruby. Using
26
- # ERB, actual Ruby code can be added to any plain text document for the
27
- # purposes of generating document information details and/or flow control.
45
+ # Before you can use \ERB, you must first require it
46
+ # (examples on this page assume that this has been done):
28
47
  #
29
- # A very simple example is this:
48
+ # ```
49
+ # require 'erb'
50
+ # ```
30
51
  #
31
- # require 'erb'
52
+ # ## In Brief
32
53
  #
33
- # x = 42
34
- # template = ERB.new <<-EOF
35
- # The value of x is: <%= x %>
36
- # EOF
37
- # puts template.result(binding)
54
+ # Here's how \ERB works:
38
55
  #
39
- # <em>Prints:</em> The value of x is: 42
56
+ # - You can create a *template*: a plain-text string that includes specially formatted *tags*..
57
+ # - You can create an \ERB object to store the template.
58
+ # - You can call instance method ERB#result to get the *result*.
40
59
  #
41
- # More complex examples are given below.
60
+ # \ERB supports tags of three kinds:
42
61
  #
62
+ # - [Expression tags][expression tags]:
63
+ # each begins with `'<%='`, ends with `'%>'`; contains a Ruby expression;
64
+ # in the result, the value of the expression replaces the entire tag:
43
65
  #
44
- # == Recognized Tags
66
+ # template = 'The magic word is <%= magic_word %>.'
67
+ # erb = ERB.new(template)
68
+ # magic_word = 'xyzzy'
69
+ # erb.result(binding) # => "The magic word is xyzzy."
45
70
  #
46
- # ERB recognizes certain tags in the provided template and converts them based
47
- # on the rules below:
71
+ # The above call to #result passes argument `binding`,
72
+ # which contains the binding of variable `magic_word` to its string value `'xyzzy'`.
48
73
  #
49
- # <% Ruby code -- inline with output %>
50
- # <%= Ruby expression -- replace with result %>
51
- # <%# comment -- ignored -- useful in testing %> (`<% #` doesn't work. Don't use Ruby comments.)
52
- # % a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
53
- # %% replaced with % if first thing on a line and % processing is used
54
- # <%% or %%> -- replace with <% or %> respectively
74
+ # The below call to #result need not pass a binding,
75
+ # because its expression `Date::DAYNAMES` is globally defined.
55
76
  #
56
- # All other text is passed through ERB filtering unchanged.
77
+ # ERB.new('Today is <%= Date::DAYNAMES[Date.today.wday] %>.').result # => "Today is Monday."
57
78
  #
79
+ # - [Execution tags][execution tags]:
80
+ # each begins with `'<%'`, ends with `'%>'`; contains Ruby code to be executed:
58
81
  #
59
- # == Options
82
+ # template = '<% File.write("t.txt", "Some stuff.") %>'
83
+ # ERB.new(template).result
84
+ # File.read('t.txt') # => "Some stuff."
60
85
  #
61
- # There are several settings you can change when you use ERB:
62
- # * the nature of the tags that are recognized;
63
- # * the binding used to resolve local variables in the template.
86
+ # - [Comment tags][comment tags]:
87
+ # each begins with `'<%#'`, ends with `'%>'`; contains comment text;
88
+ # in the result, the entire tag is omitted.
64
89
  #
65
- # See the ERB.new and ERB#result methods for more detail.
90
+ # template = 'Some stuff;<%# Note to self: figure out what the stuff is. %> more stuff.'
91
+ # ERB.new(template).result # => "Some stuff; more stuff."
66
92
  #
67
- # == Character encodings
93
+ # ## Some Simple Examples
68
94
  #
69
- # ERB (or Ruby code generated by ERB) returns a string in the same
70
- # character encoding as the input string. When the input string has
71
- # a magic comment, however, it returns a string in the encoding specified
72
- # by the magic comment.
95
+ # Here's a simple example of \ERB in action:
73
96
  #
74
- # # -*- coding: utf-8 -*-
75
- # require 'erb'
97
+ # ```
98
+ # template = 'The time is <%= Time.now %>.'
99
+ # erb = ERB.new(template)
100
+ # erb.result
101
+ # # => "The time is 2025-09-09 10:49:26 -0500."
102
+ # ```
76
103
  #
77
- # template = ERB.new <<EOF
78
- # <%#-*- coding: Big5 -*-%>
79
- # \_\_ENCODING\_\_ is <%= \_\_ENCODING\_\_ %>.
80
- # EOF
81
- # puts template.result
104
+ # Details:
82
105
  #
83
- # <em>Prints:</em> \_\_ENCODING\_\_ is Big5.
106
+ # 1. A plain-text string is assigned to variable `template`.
107
+ # Its embedded [expression tag][expression tags] `'<%= Time.now %>'` includes a Ruby expression, `Time.now`.
108
+ # 2. The string is put into a new \ERB object, and stored in variable `erb`.
109
+ # 4. Method call `erb.result` generates a string that contains the run-time value of `Time.now`,
110
+ # as computed at the time of the call.
84
111
  #
112
+ # The
113
+ # \ERB object may be re-used:
85
114
  #
86
- # == Examples
115
+ # ```
116
+ # erb.result
117
+ # # => "The time is 2025-09-09 10:49:33 -0500."
118
+ # ```
87
119
  #
88
- # === Plain Text
120
+ # Another example:
89
121
  #
90
- # ERB is useful for any generic templating situation. Note that in this example, we use the
91
- # convenient "% at start of line" tag, and we quote the template literally with
92
- # <tt>%q{...}</tt> to avoid trouble with the backslash.
122
+ # ```
123
+ # template = 'The magic word is <%= magic_word %>.'
124
+ # erb = ERB.new(template)
125
+ # magic_word = 'abracadabra'
126
+ # erb.result(binding)
127
+ # # => "The magic word is abracadabra."
128
+ # ```
93
129
  #
94
- # require "erb"
130
+ # Details:
95
131
  #
96
- # # Create template.
97
- # template = %q{
98
- # From: James Edward Gray II <james@grayproductions.net>
99
- # To: <%= to %>
100
- # Subject: Addressing Needs
132
+ # 1. As before, a plain-text string is assigned to variable `template`.
133
+ # Its embedded [expression tag][expression tags] `'<%= magic_word %>'` has a variable *name*, `magic_word`.
134
+ # 2. The string is put into a new \ERB object, and stored in variable `erb`;
135
+ # note that `magic_word` need not be defined before the \ERB object is created.
136
+ # 3. `magic_word = 'abracadabra'` assigns a value to variable `magic_word`.
137
+ # 4. Method call `erb.result(binding)` generates a string
138
+ # that contains the *value* of `magic_word`.
101
139
  #
102
- # <%= to[/\w+/] %>:
140
+ # As before, the \ERB object may be re-used:
103
141
  #
104
- # Just wanted to send a quick note assuring that your needs are being
105
- # addressed.
142
+ # ```
143
+ # magic_word = 'xyzzy'
144
+ # erb.result(binding)
145
+ # # => "The magic word is xyzzy."
146
+ # ```
106
147
  #
107
- # I want you to know that my team will keep working on the issues,
108
- # especially:
148
+ # ## Bindings
109
149
  #
110
- # <%# ignore numerous minor requests -- focus on priorities %>
111
- # % priorities.each do |priority|
112
- # * <%= priority %>
113
- # % end
150
+ # A call to method #result, which produces the formatted result string,
151
+ # requires a [Binding object][binding object] as its argument.
152
+ #
153
+ # The binding object provides the bindings for expressions in [expression tags][expression tags].
154
+ #
155
+ # There are three ways to provide the required binding:
156
+ #
157
+ # - [Default binding][default binding].
158
+ # - [Local binding][local binding].
159
+ # - [Augmented binding][augmented binding]
160
+ #
161
+ # ### Default Binding
162
+ #
163
+ # When you pass no `binding` argument to method #result,
164
+ # the method uses its default binding: the one returned by method #new_toplevel.
165
+ # This binding has the bindings defined by Ruby itself,
166
+ # which are those for Ruby's constants and variables.
167
+ #
168
+ # That binding is sufficient for an expression tag that refers only to Ruby's constants and variables;
169
+ # these expression tags refer only to Ruby's global constant `RUBY_COPYRIGHT` and global variable `$0`:
114
170
  #
115
- # Thanks for your patience.
171
+ # ```
172
+ # template = <<TEMPLATE
173
+ # The Ruby copyright is <%= RUBY_COPYRIGHT.inspect %>.
174
+ # The current process is <%= $0 %>.
175
+ # TEMPLATE
176
+ # puts ERB.new(template).result
177
+ # The Ruby copyright is "ruby - Copyright (C) 1993-2025 Yukihiro Matsumoto".
178
+ # The current process is irb.
179
+ # ```
180
+ #
181
+ # (The current process is `irb` because that's where we're doing these examples!)
182
+ #
183
+ # ### Local Binding
184
+ #
185
+ # The default binding is *not* sufficient for an expression
186
+ # that refers to a a constant or variable that is not defined there:
187
+ #
188
+ # ```
189
+ # Foo = 1 # Defines local constant Foo.
190
+ # foo = 2 # Defines local variable foo.
191
+ # template = <<TEMPLATE
192
+ # The current value of constant Foo is <%= Foo %>.
193
+ # The current value of variable foo is <%= foo %>.
194
+ # The Ruby copyright is <%= RUBY_COPYRIGHT.inspect %>.
195
+ # The current process is <%= $0 %>.
196
+ # TEMPLATE
197
+ # erb = ERB.new(template)
198
+ # ```
199
+ #
200
+ # This call below raises `NameError` because although `Foo` and `foo` are defined locally,
201
+ # they are not defined in the default binding:
202
+ #
203
+ # ```
204
+ # erb.result # Raises NameError.
205
+ # ```
206
+ #
207
+ # To make the locally-defined constants and variables available,
208
+ # you can call #result with the local binding:
209
+ #
210
+ # ```
211
+ # puts erb.result(binding)
212
+ # The current value of constant Foo is 1.
213
+ # The current value of variable foo is 2.
214
+ # The Ruby copyright is "ruby - Copyright (C) 1993-2025 Yukihiro Matsumoto".
215
+ # The current process is irb.
216
+ # ```
217
+ #
218
+ # ### Augmented Binding
219
+ #
220
+ # Another way to make variable bindings (but not constant bindings) available
221
+ # is to use method #result_with_hash(hash);
222
+ # the passed hash has name/value pairs that are to be used to define and assign variables
223
+ # in a copy of the default binding:
224
+ #
225
+ # ```
226
+ # template = <<TEMPLATE
227
+ # The current value of variable bar is <%= bar %>.
228
+ # The current value of variable baz is <%= baz %>.
229
+ # The Ruby copyright is <%= RUBY_COPYRIGHT.inspect %>.
230
+ # The current process is <%= $0 %>.
231
+ # TEMPLATE
232
+ # erb = ERB.new(template)
233
+ # ```
234
+ #
235
+ # Both of these calls raise `NameError`, because `bar` and `baz`
236
+ # are not defined in either the default binding or the local binding.
237
+ #
238
+ # ```
239
+ # puts erb.result # Raises NameError.
240
+ # puts erb.result(binding) # Raises NameError.
241
+ # ```
242
+ #
243
+ # This call passes a hash that causes `bar` and `baz` to be defined
244
+ # in a new binding (derived from #new_toplevel):
245
+ #
246
+ # ```
247
+ # hash = {bar: 3, baz: 4}
248
+ # puts erb.result_with_hash(hash)
249
+ # The current value of variable bar is 3.
250
+ # The current value of variable baz is 4.
251
+ # The Ruby copyright is "ruby - Copyright (C) 1993-2025 Yukihiro Matsumoto".
252
+ # The current process is irb.
253
+ # ```
254
+ #
255
+ # ## Tags
256
+ #
257
+ # The examples above use expression tags.
258
+ # These are the tags available in \ERB:
259
+ #
260
+ # - [Expression tag][expression tags]: the tag contains a Ruby expression;
261
+ # in the result, the entire tag is to be replaced with the run-time value of the expression.
262
+ # - [Execution tag][execution tags]: the tag contains Ruby code;
263
+ # in the result, the entire tag is to be replaced with the run-time value of the code.
264
+ # - [Comment tag][comment tags]: the tag contains comment code;
265
+ # in the result, the entire tag is to be omitted.
266
+ #
267
+ # ### Expression Tags
268
+ #
269
+ # You can embed a Ruby expression in a template using an *expression tag*.
270
+ #
271
+ # Its syntax is `<%= _expression_ %>`,
272
+ # where *expression* is any valid Ruby expression.
273
+ #
274
+ # When you call method #result,
275
+ # the method evaluates the expression and replaces the entire expression tag with the expression's value:
276
+ #
277
+ # ```
278
+ # ERB.new('Today is <%= Date::DAYNAMES[Date.today.wday] %>.').result
279
+ # # => "Today is Monday."
280
+ # ERB.new('Tomorrow will be <%= Date::DAYNAMES[Date.today.wday + 1] %>.').result
281
+ # # => "Tomorrow will be Tuesday."
282
+ # ERB.new('Yesterday was <%= Date::DAYNAMES[Date.today.wday - 1] %>.').result
283
+ # # => "Yesterday was Sunday."
284
+ # ```
285
+ #
286
+ # Note that whitespace before and after the expression
287
+ # is allowed but not required,
288
+ # and that such whitespace is stripped from the result.
289
+ #
290
+ # ```
291
+ # ERB.new('My appointment is on <%=Date::DAYNAMES[Date.today.wday + 2]%>.').result
292
+ # # => "My appointment is on Wednesday."
293
+ # ERB.new('My appointment is on <%= Date::DAYNAMES[Date.today.wday + 2] %>.').result
294
+ # # => "My appointment is on Wednesday."
295
+ # ```
296
+ #
297
+ # ### Execution Tags
298
+ #
299
+ # You can embed Ruby executable code in template using an *execution tag*.
300
+ #
301
+ # Its syntax is `<% _code_ %>`,
302
+ # where *code* is any valid Ruby code.
303
+ #
304
+ # When you call method #result,
305
+ # the method executes the code and removes the entire execution tag
306
+ # (generating no text in the result):
307
+ #
308
+ # ```
309
+ # ERB.new('foo <% Dir.chdir("C:/") %> bar').result # => "foo bar"
310
+ # ```
311
+ #
312
+ # Whitespace before and after the embedded code is optional:
313
+ #
314
+ # ```
315
+ # ERB.new('foo <%Dir.chdir("C:/")%> bar').result # => "foo bar"
316
+ # ```
317
+ #
318
+ # You can interleave text with execution tags to form a control structure
319
+ # such as a conditional, a loop, or a `case` statements.
320
+ #
321
+ # Conditional:
322
+ #
323
+ # ```
324
+ # template = <<TEMPLATE
325
+ # <% if verbosity %>
326
+ # An error has occurred.
327
+ # <% else %>
328
+ # Oops!
329
+ # <% end %>
330
+ # TEMPLATE
331
+ # erb = ERB.new(template)
332
+ # verbosity = true
333
+ # erb.result(binding)
334
+ # # => "\nAn error has occurred.\n\n"
335
+ # verbosity = false
336
+ # erb.result(binding)
337
+ # # => "\nOops!\n\n"
338
+ # ```
339
+ #
340
+ # Note that the interleaved text may itself contain expression tags:
341
+ #
342
+ # Loop:
343
+ #
344
+ # ```
345
+ # template = <<TEMPLATE
346
+ # <% Date::ABBR_DAYNAMES.each do |dayname| %>
347
+ # <%= dayname %>
348
+ # <% end %>
349
+ # TEMPLATE
350
+ # ERB.new(template).result
351
+ # # => "\nSun\n\nMon\n\nTue\n\nWed\n\nThu\n\nFri\n\nSat\n\n"
352
+ # ```
353
+ #
354
+ # Other, non-control, lines of Ruby code may be interleaved with the text,
355
+ # and the Ruby code may itself contain regular Ruby comments:
356
+ #
357
+ # ```
358
+ # template = <<TEMPLATE
359
+ # <% 3.times do %>
360
+ # <%= Time.now %>
361
+ # <% sleep(1) # Let's make the times different. %>
362
+ # <% end %>
363
+ # TEMPLATE
364
+ # ERB.new(template).result
365
+ # # => "\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"
366
+ # ```
367
+ #
368
+ # The execution tag may also contain multiple lines of code:
369
+ #
370
+ # ```
371
+ # template = <<TEMPLATE
372
+ # <%
373
+ # (0..2).each do |i|
374
+ # (0..2).each do |j|
375
+ # %>
376
+ # * <%=i%>,<%=j%>
377
+ # <%
378
+ # end
379
+ # end
380
+ # %>
381
+ # TEMPLATE
382
+ # ERB.new(template).result
383
+ # # => "\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"
384
+ # ```
385
+ #
386
+ # #### Shorthand Format for Execution Tags
387
+ #
388
+ # You can use keyword argument `trim_mode: '%'` to enable a shorthand format for execution tags;
389
+ # this example uses the shorthand format `% _code_` instead of `<% _code_ %>`:
390
+ #
391
+ # ```
392
+ # template = <<TEMPLATE
393
+ # % priorities.each do |priority|
394
+ # * <%= priority %>
395
+ # % end
396
+ # TEMPLATE
397
+ # erb = ERB.new(template, trim_mode: '%')
398
+ # priorities = [ 'Run Ruby Quiz',
399
+ # 'Document Modules',
400
+ # 'Answer Questions on Ruby Talk' ]
401
+ # puts erb.result(binding)
402
+ # * Run Ruby Quiz
403
+ # * Document Modules
404
+ # * Answer Questions on Ruby Talk
405
+ # ```
406
+ #
407
+ # Note that in the shorthand format, the character `'%'` must be the first character in the code line
408
+ # (no leading whitespace).
409
+ #
410
+ # #### Suppressing Unwanted Blank Lines
411
+ #
412
+ # With keyword argument `trim_mode` not given,
413
+ # all blank lines go into the result:
414
+ #
415
+ # ```
416
+ # template = <<TEMPLATE
417
+ # <% if true %>
418
+ # <%= RUBY_VERSION %>
419
+ # <% end %>
420
+ # TEMPLATE
421
+ # ERB.new(template).result.lines.each {|line| puts line.inspect }
422
+ # "\n"
423
+ # "3.4.5\n"
424
+ # "\n"
425
+ # ```
426
+ #
427
+ # You can give `trim_mode: '-'`, you can suppress each blank line
428
+ # whose source line ends with `-%>` (instead of `%>`):
429
+ #
430
+ # ```
431
+ # template = <<TEMPLATE
432
+ # <% if true -%>
433
+ # <%= RUBY_VERSION %>
434
+ # <% end -%>
435
+ # TEMPLATE
436
+ # ERB.new(template, trim_mode: '-').result.lines.each {|line| puts line.inspect }
437
+ # "3.4.5\n"
438
+ # ```
439
+ #
440
+ # It is an error to use the trailing `'-%>'` notation without `trim_mode: '-'`:
441
+ #
442
+ # ```
443
+ # ERB.new(template).result.lines.each {|line| puts line.inspect } # Raises SyntaxError.
444
+ # ```
445
+ #
446
+ # #### Suppressing Unwanted Newlines
447
+ #
448
+ # Consider this template:
449
+ #
450
+ # ```
451
+ # template = <<TEMPLATE
452
+ # <% RUBY_VERSION %>
453
+ # <%= RUBY_VERSION %>
454
+ # foo <% RUBY_VERSION %>
455
+ # foo <%= RUBY_VERSION %>
456
+ # TEMPLATE
457
+ # ```
458
+ #
459
+ # With keyword argument `trim_mode` not given, all newlines go into the result:
460
+ #
461
+ # ```
462
+ # ERB.new(template).result.lines.each {|line| puts line.inspect }
463
+ # "\n"
464
+ # "3.4.5\n"
465
+ # "foo \n"
466
+ # "foo 3.4.5\n"
467
+ # ```
468
+ #
469
+ # You can give `trim_mode: '>'` to suppress the trailing newline
470
+ # for each line that ends with `'%>'` (regardless of its beginning):
471
+ #
472
+ # ```
473
+ # ERB.new(template, trim_mode: '>').result.lines.each {|line| puts line.inspect }
474
+ # "3.4.5foo foo 3.4.5"
475
+ # ```
476
+ #
477
+ # You can give `trim_mode: '<>'` to suppress the trailing newline
478
+ # for each line that both begins with `'<%'` and ends with `'%>'`:
479
+ #
480
+ # ```
481
+ # ERB.new(template, trim_mode: '<>').result.lines.each {|line| puts line.inspect }
482
+ # "3.4.5foo \n"
483
+ # "foo 3.4.5\n"
484
+ # ```
485
+ #
486
+ # #### Combining Trim Modes
487
+ #
488
+ # You can combine certain trim modes:
489
+ #
490
+ # - `'%-'`: Enable shorthand and omit each blank line ending with `'-%>'`.
491
+ # - `'%>'`: Enable shorthand and omit newline for each line ending with `'%>'`.
492
+ # - `'%<>'`: Enable shorthand and omit newline for each line starting with `'<%'` and ending with `'%>'`.
493
+ #
494
+ # ### Comment Tags
495
+ #
496
+ # You can embed a comment in a template using a *comment tag*;
497
+ # its syntax is `<%# _text_ %>`,
498
+ # where *text* is the text of the comment.
499
+ #
500
+ # When you call method #result,
501
+ # it removes the entire comment tag
502
+ # (generating no text in the result).
503
+ #
504
+ # Example:
505
+ #
506
+ # ```
507
+ # template = 'Some stuff;<%# Note to self: figure out what the stuff is. %> more stuff.'
508
+ # ERB.new(template).result # => "Some stuff; more stuff."
509
+ # ```
510
+ #
511
+ # A comment tag may appear anywhere in the template.
512
+ #
513
+ # Note that the beginning of the tag must be `'<%#'`, not `'<% #'`.
514
+ #
515
+ # In this example, the tag begins with `'<% #'`, and so is an execution tag, not a comment tag;
516
+ # the cited code consists entirely of a Ruby-style comment (which is of course ignored):
517
+ #
518
+ # ```
519
+ # ERB.new('Some stuff;<% # Note to self: figure out what the stuff is. %> more stuff.').result
520
+ # # => "Some stuff;"
521
+ # ```
522
+ #
523
+ # ## Encodings
524
+ #
525
+ # An \ERB object has an [encoding][encoding],
526
+ # which is by default the encoding of the template string;
527
+ # the result string will also have that encoding.
116
528
  #
117
- # James Edward Gray II
118
- # }.gsub(/^ /, '')
529
+ # ```
530
+ # template = <<TEMPLATE
531
+ # <%# Comment. %>
532
+ # TEMPLATE
533
+ # erb = ERB.new(template)
534
+ # template.encoding # => #<Encoding:UTF-8>
535
+ # erb.encoding # => #<Encoding:UTF-8>
536
+ # erb.result.encoding # => #<Encoding:UTF-8>
537
+ # ```
119
538
  #
120
- # message = ERB.new(template, trim_mode: "%<>")
539
+ # You can specify a different encoding by adding a [magic comment][magic comments]
540
+ # at the top of the given template:
121
541
  #
122
- # # Set up template data.
123
- # to = "Community Spokesman <spokesman@ruby_community.org>"
124
- # priorities = [ "Run Ruby Quiz",
125
- # "Document Modules",
126
- # "Answer Questions on Ruby Talk" ]
542
+ # ```
543
+ # template = <<TEMPLATE
544
+ # <%#-*- coding: Big5 -*-%>
545
+ # <%# Comment. %>
546
+ # TEMPLATE
547
+ # erb = ERB.new(template)
548
+ # template.encoding # => #<Encoding:UTF-8>
549
+ # erb.encoding # => #<Encoding:Big5>
550
+ # erb.result.encoding # => #<Encoding:Big5>
551
+ # ```
127
552
  #
128
- # # Produce result.
129
- # email = message.result
130
- # puts email
553
+ # ## Error Reporting
131
554
  #
132
- # <i>Generates:</i>
555
+ # Consider this template (containing an error):
133
556
  #
134
- # From: James Edward Gray II <james@grayproductions.net>
135
- # To: Community Spokesman <spokesman@ruby_community.org>
136
- # Subject: Addressing Needs
557
+ # ```
558
+ # template = '<%= nosuch %>'
559
+ # erb = ERB.new(template)
560
+ # ```
137
561
  #
138
- # Community:
562
+ # When \ERB reports an error,
563
+ # it includes a file name (if available) and a line number;
564
+ # the file name comes from method #filename, the line number from method #lineno.
139
565
  #
140
- # Just wanted to send a quick note assuring that your needs are being addressed.
566
+ # Initially, those values are `nil` and `0`, respectively;
567
+ # these initial values are reported as `'(erb)'` and `1`, respectively:
141
568
  #
142
- # I want you to know that my team will keep working on the issues, especially:
569
+ # ```
570
+ # erb.filename # => nil
571
+ # erb.lineno # => 0
572
+ # erb.result
573
+ # (erb):1:in '<main>': undefined local variable or method 'nosuch' for main (NameError)
574
+ # ```
143
575
  #
144
- # * Run Ruby Quiz
145
- # * Document Modules
146
- # * Answer Questions on Ruby Talk
576
+ # You can use methods #filename= and #lineno= to assign values
577
+ # that are more meaningful in your context:
147
578
  #
148
- # Thanks for your patience.
579
+ # ```
580
+ # erb.filename = 't.txt'
581
+ # erb.lineno = 555
582
+ # erb.result
583
+ # t.txt:556:in '<main>': undefined local variable or method 'nosuch' for main (NameError)
584
+ # ```
149
585
  #
150
- # James Edward Gray II
586
+ # You can use method #location= to set both values:
151
587
  #
152
- # === Ruby in HTML
588
+ # ```
589
+ # erb.location = ['u.txt', 999]
590
+ # erb.result
591
+ # u.txt:1000:in '<main>': undefined local variable or method 'nosuch' for main (NameError)
592
+ # ```
153
593
  #
154
- # ERB is often used in <tt>.rhtml</tt> files (HTML with embedded Ruby). Notice the need in
155
- # this example to provide a special binding when the template is run, so that the instance
156
- # variables in the Product object can be resolved.
594
+ # ## Plain Text with Embedded Ruby
157
595
  #
158
- # require "erb"
596
+ # Here's a plain-text template;
597
+ # it uses the literal notation `'%q{ ... }'` to define the template
598
+ # (see [%q literals][%q literals]);
599
+ # this avoids problems with backslashes.
159
600
  #
160
- # # Build template data class.
161
- # class Product
162
- # def initialize( code, name, desc, cost )
163
- # @code = code
164
- # @name = name
165
- # @desc = desc
166
- # @cost = cost
601
+ # ```
602
+ # template = %q{
603
+ # From: James Edward Gray II <james@grayproductions.net>
604
+ # To: <%= to %>
605
+ # Subject: Addressing Needs
167
606
  #
168
- # @features = [ ]
169
- # end
607
+ # <%= to[/\w+/] %>:
170
608
  #
171
- # def add_feature( feature )
172
- # @features << feature
173
- # end
609
+ # Just wanted to send a quick note assuring that your needs are being
610
+ # addressed.
174
611
  #
175
- # # Support templating of member data.
176
- # def get_binding
177
- # binding
178
- # end
612
+ # I want you to know that my team will keep working on the issues,
613
+ # especially:
179
614
  #
180
- # # ...
181
- # end
615
+ # <%# ignore numerous minor requests -- focus on priorities %>
616
+ # % priorities.each do |priority|
617
+ # * <%= priority %>
618
+ # % end
182
619
  #
183
- # # Create template.
184
- # template = %{
185
- # <html>
186
- # <head><title>Ruby Toys -- <%= @name %></title></head>
187
- # <body>
620
+ # Thanks for your patience.
188
621
  #
189
- # <h1><%= @name %> (<%= @code %>)</h1>
190
- # <p><%= @desc %></p>
622
+ # James Edward Gray II
623
+ # }
624
+ # ```
191
625
  #
192
- # <ul>
193
- # <% @features.each do |f| %>
194
- # <li><b><%= f %></b></li>
195
- # <% end %>
196
- # </ul>
626
+ # The template will need these:
197
627
  #
198
- # <p>
199
- # <% if @cost < 10 %>
200
- # <b>Only <%= @cost %>!!!</b>
201
- # <% else %>
202
- # Call for a price, today!
203
- # <% end %>
204
- # </p>
628
+ # ```
629
+ # to = 'Community Spokesman <spokesman@ruby_community.org>'
630
+ # priorities = [ 'Run Ruby Quiz',
631
+ # 'Document Modules',
632
+ # 'Answer Questions on Ruby Talk' ]
633
+ # ```
205
634
  #
206
- # </body>
207
- # </html>
208
- # }.gsub(/^ /, '')
635
+ # Finally, create the \ERB object and get the result
209
636
  #
210
- # rhtml = ERB.new(template)
637
+ # ```
638
+ # erb = ERB.new(template, trim_mode: '%<>')
639
+ # puts erb.result(binding)
211
640
  #
212
- # # Set up template data.
213
- # toy = Product.new( "TZ-1002",
214
- # "Rubysapien",
215
- # "Geek's Best Friend! Responds to Ruby commands...",
216
- # 999.95 )
217
- # toy.add_feature("Listens for verbal commands in the Ruby language!")
218
- # toy.add_feature("Ignores Perl, Java, and all C variants.")
219
- # toy.add_feature("Karate-Chop Action!!!")
220
- # toy.add_feature("Matz signature on left leg.")
221
- # toy.add_feature("Gem studded eyes... Rubies, of course!")
641
+ # From: James Edward Gray II <james@grayproductions.net>
642
+ # To: Community Spokesman <spokesman@ruby_community.org>
643
+ # Subject: Addressing Needs
222
644
  #
223
- # # Produce result.
224
- # rhtml.run(toy.get_binding)
645
+ # Community:
225
646
  #
226
- # <i>Generates (some blank lines removed):</i>
647
+ # Just wanted to send a quick note assuring that your needs are being
648
+ # addressed.
227
649
  #
228
- # <html>
229
- # <head><title>Ruby Toys -- Rubysapien</title></head>
230
- # <body>
650
+ # I want you to know that my team will keep working on the issues,
651
+ # especially:
231
652
  #
232
- # <h1>Rubysapien (TZ-1002)</h1>
233
- # <p>Geek's Best Friend! Responds to Ruby commands...</p>
653
+ # * Run Ruby Quiz
654
+ # * Document Modules
655
+ # * Answer Questions on Ruby Talk
234
656
  #
235
- # <ul>
236
- # <li><b>Listens for verbal commands in the Ruby language!</b></li>
237
- # <li><b>Ignores Perl, Java, and all C variants.</b></li>
238
- # <li><b>Karate-Chop Action!!!</b></li>
239
- # <li><b>Matz signature on left leg.</b></li>
240
- # <li><b>Gem studded eyes... Rubies, of course!</b></li>
241
- # </ul>
657
+ # Thanks for your patience.
242
658
  #
243
- # <p>
244
- # Call for a price, today!
245
- # </p>
659
+ # James Edward Gray II
660
+ # ```
246
661
  #
247
- # </body>
248
- # </html>
662
+ # ## HTML with Embedded Ruby
249
663
  #
664
+ # This example shows an HTML template.
250
665
  #
251
- # == Notes
666
+ # First, here's a custom class, `Product`:
252
667
  #
253
- # There are a variety of templating solutions available in various Ruby projects.
254
- # For example, RDoc, distributed with Ruby, uses its own template engine, which
255
- # can be reused elsewhere.
668
+ # ```
669
+ # class Product
670
+ # def initialize(code, name, desc, cost)
671
+ # @code = code
672
+ # @name = name
673
+ # @desc = desc
674
+ # @cost = cost
675
+ # @features = []
676
+ # end
256
677
  #
257
- # Other popular engines could be found in the corresponding
258
- # {Category}[https://www.ruby-toolbox.com/categories/template_engines] of
259
- # The Ruby Toolbox.
678
+ # def add_feature(feature)
679
+ # @features << feature
680
+ # end
681
+ #
682
+ # # Support templating of member data.
683
+ # def get_binding
684
+ # binding
685
+ # end
686
+ #
687
+ # end
688
+ # ```
689
+ #
690
+ # The template below will need these values:
691
+ #
692
+ # ```
693
+ # toy = Product.new('TZ-1002',
694
+ # 'Rubysapien',
695
+ # "Geek's Best Friend! Responds to Ruby commands...",
696
+ # 999.95
697
+ # )
698
+ # toy.add_feature('Listens for verbal commands in the Ruby language!')
699
+ # toy.add_feature('Ignores Perl, Java, and all C variants.')
700
+ # toy.add_feature('Karate-Chop Action!!!')
701
+ # toy.add_feature('Matz signature on left leg.')
702
+ # toy.add_feature('Gem studded eyes... Rubies, of course!')
703
+ # ```
704
+ #
705
+ # Here's the HTML:
706
+ #
707
+ # ```
708
+ # template = <<TEMPLATE
709
+ # <html>
710
+ # <head><title>Ruby Toys -- <%= @name %></title></head>
711
+ # <body>
712
+ # <h1><%= @name %> (<%= @code %>)</h1>
713
+ # <p><%= @desc %></p>
714
+ # <ul>
715
+ # <% @features.each do |f| %>
716
+ # <li><b><%= f %></b></li>
717
+ # <% end %>
718
+ # </ul>
719
+ # <p>
720
+ # <% if @cost < 10 %>
721
+ # <b>Only <%= @cost %>!!!</b>
722
+ # <% else %>
723
+ # Call for a price, today!
724
+ # <% end %>
725
+ # </p>
726
+ # </body>
727
+ # </html>
728
+ # TEMPLATE
729
+ # ```
730
+ #
731
+ # Finally, create the \ERB object and get the result (omitting some blank lines):
732
+ #
733
+ # ```
734
+ # erb = ERB.new(template)
735
+ # puts erb.result(toy.get_binding)
736
+ # <html>
737
+ # <head><title>Ruby Toys -- Rubysapien</title></head>
738
+ # <body>
739
+ # <h1>Rubysapien (TZ-1002)</h1>
740
+ # <p>Geek's Best Friend! Responds to Ruby commands...</p>
741
+ # <ul>
742
+ # <li><b>Listens for verbal commands in the Ruby language!</b></li>
743
+ # <li><b>Ignores Perl, Java, and all C variants.</b></li>
744
+ # <li><b>Karate-Chop Action!!!</b></li>
745
+ # <li><b>Matz signature on left leg.</b></li>
746
+ # <li><b>Gem studded eyes... Rubies, of course!</b></li>
747
+ # </ul>
748
+ # <p>
749
+ # Call for a price, today!
750
+ # </p>
751
+ # </body>
752
+ # </html>
753
+ # ```
754
+ #
755
+ #
756
+ # ## Other Template Processors
757
+ #
758
+ # Various Ruby projects have their own template processors.
759
+ # The Ruby Processing System [RDoc][rdoc], for example, has one that can be used elsewhere.
760
+ #
761
+ # Other popular template processors may found in the [Template Engines][template engines] page
762
+ # of the Ruby Toolbox.
763
+ #
764
+ # [%q literals]: https://docs.ruby-lang.org/en/master/syntax/literals_rdoc.html#label-25q-3A+Non-Interpolable+String+Literals
765
+ # [augmented binding]: rdoc-ref:ERB@Augmented+Binding
766
+ # [binding object]: https://docs.ruby-lang.org/en/master/Binding.html
767
+ # [comment tags]: rdoc-ref:ERB@Comment+Tags
768
+ # [default binding]: rdoc-ref:ERB@Default+Binding
769
+ # [encoding]: https://docs.ruby-lang.org/en/master/Encoding.html
770
+ # [execution tags]: rdoc-ref:ERB@Execution+Tags
771
+ # [expression tags]: rdoc-ref:ERB@Expression+Tags
772
+ # [kernel#binding]: https://docs.ruby-lang.org/en/master/Kernel.html#method-i-binding
773
+ # [local binding]: rdoc-ref:ERB@Local+Binding
774
+ # [magic comments]: https://docs.ruby-lang.org/en/master/syntax/comments_rdoc.html#label-Magic+Comments
775
+ # [rdoc]: https://ruby.github.io/rdoc
776
+ # [sprintf]: https://docs.ruby-lang.org/en/master/Kernel.html#method-i-sprintf
777
+ # [template engines]: https://www.ruby-toolbox.com/categories/template_engines
778
+ # [template processor]: https://en.wikipedia.org/wiki/Template_processor
260
779
  #
261
780
  class ERB
262
- Revision = '$Date:: $' # :nodoc: #'
263
- deprecate_constant :Revision
264
-
265
- # Returns revision information for the erb.rb module.
781
+ # :markup: markdown
782
+ #
783
+ # :call-seq:
784
+ # self.version -> string
785
+ #
786
+ # Returns the string \ERB version.
266
787
  def self.version
267
788
  VERSION
268
789
  end
269
790
 
791
+ # :markup: markdown
270
792
  #
271
- # Constructs a new ERB object with the template specified in _str_.
793
+ # :call-seq:
794
+ # ERB.new(template, trim_mode: nil, eoutvar: '_erbout')
272
795
  #
273
- # An ERB object works by building a chunk of Ruby code that will output
274
- # the completed template when run.
796
+ # Returns a new \ERB object containing the given string +template+.
275
797
  #
276
- # If _trim_mode_ is passed a String containing one or more of the following
277
- # modifiers, ERB will adjust its code generation as listed:
798
+ # For details about `template`, its embedded tags, and generated results, see ERB.
278
799
  #
279
- # % enables Ruby code processing for lines beginning with %
280
- # <> omit newline for lines starting with <% and ending in %>
281
- # > omit newline for lines ending in %>
282
- # - omit blank lines ending in -%>
800
+ # **Keyword Argument `trim_mode`**
283
801
  #
284
- # _eoutvar_ can be used to set the name of the variable ERB will build up
285
- # its output in. This is useful when you need to run multiple ERB
286
- # templates through the same binding and/or when you want to control where
287
- # output ends up. Pass the name of the variable to be used inside a String.
802
+ # You can use keyword argument `trim_mode: '%'`
803
+ # to enable the [shorthand format][shorthand format] for execution tags.
288
804
  #
289
- # === Example
805
+ # This value allows [blank line control][blank line control]:
290
806
  #
291
- # require "erb"
807
+ # - `'-'`: Omit each blank line ending with `'%>'`.
292
808
  #
293
- # # build data class
294
- # class Listings
295
- # PRODUCT = { :name => "Chicken Fried Steak",
296
- # :desc => "A well messaged pattie, breaded and fried.",
297
- # :cost => 9.95 }
809
+ # Other values allow [newline control][newline control]:
298
810
  #
299
- # attr_reader :product, :price
811
+ # - `'>'`: Omit newline for each line ending with `'%>'`.
812
+ # - `'<>'`: Omit newline for each line starting with `'<%'` and ending with `'%>'`.
300
813
  #
301
- # def initialize( product = "", price = "" )
302
- # @product = product
303
- # @price = price
304
- # end
814
+ # You can also [combine trim modes][combine trim modes].
305
815
  #
306
- # def build
307
- # b = binding
308
- # # create and run templates, filling member data variables
309
- # ERB.new(<<~'END_PRODUCT', trim_mode: "", eoutvar: "@product").result b
310
- # <%= PRODUCT[:name] %>
311
- # <%= PRODUCT[:desc] %>
312
- # END_PRODUCT
313
- # ERB.new(<<~'END_PRICE', trim_mode: "", eoutvar: "@price").result b
314
- # <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
315
- # <%= PRODUCT[:desc] %>
316
- # END_PRICE
317
- # end
318
- # end
816
+ # **Keyword Argument `eoutvar`**
319
817
  #
320
- # # setup template data
321
- # listings = Listings.new
322
- # listings.build
818
+ # The string value of keyword argument `eoutvar` specifies the name of the variable
819
+ # that method #result uses to construct its result string;
820
+ # see #src.
323
821
  #
324
- # puts listings.product + "\n" + listings.price
822
+ # This is useful when you need to run multiple \ERB templates through the same binding
823
+ # and/or when you want to control where output ends up.
325
824
  #
326
- # _Generates_
825
+ # It's good practice to choose a variable name that begins with an underscore: `'_'`.
327
826
  #
328
- # Chicken Fried Steak
329
- # A well massaged pattie, breaded and fried.
827
+ # [blank line control]: rdoc-ref:ERB@Suppressing+Unwanted+Blank+Lines
828
+ # [combine trim modes]: rdoc-ref:ERB@Combining+Trim+Modes
829
+ # [newline control]: rdoc-ref:ERB@Suppressing+Unwanted+Newlines
830
+ # [shorthand format]: rdoc-ref:ERB@Shorthand+Format+for+Execution+Tags
330
831
  #
331
- # Chicken Fried Steak -- 9.95
332
- # A well massaged pattie, breaded and fried.
333
- #
334
- def initialize(str, safe_level=NOT_GIVEN, legacy_trim_mode=NOT_GIVEN, legacy_eoutvar=NOT_GIVEN, trim_mode: nil, eoutvar: '_erbout')
335
- # Complex initializer for $SAFE deprecation at [Feature #14256]. Use keyword arguments to pass trim_mode or eoutvar.
336
- if safe_level != NOT_GIVEN
337
- warn 'Passing safe_level with the 2nd argument of ERB.new is deprecated. Do not use it, and specify other arguments as keyword arguments.', uplevel: 1
338
- end
339
- if legacy_trim_mode != NOT_GIVEN
340
- warn 'Passing trim_mode with the 3rd argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, trim_mode: ...) instead.', uplevel: 1
341
- trim_mode = legacy_trim_mode
342
- end
343
- if legacy_eoutvar != NOT_GIVEN
344
- warn 'Passing eoutvar with the 4th argument of ERB.new is deprecated. Use keyword argument like ERB.new(str, eoutvar: ...) instead.', uplevel: 1
345
- eoutvar = legacy_eoutvar
346
- end
347
-
832
+ def initialize(str, trim_mode: nil, eoutvar: '_erbout')
348
833
  compiler = make_compiler(trim_mode)
349
834
  set_eoutvar(compiler, eoutvar)
350
835
  @src, @encoding, @frozen_string = *compiler.compile(str)
@@ -352,54 +837,137 @@ class ERB
352
837
  @lineno = 0
353
838
  @_init = self.class.singleton_class
354
839
  end
355
- NOT_GIVEN = defined?(Ractor) ? Ractor.make_shareable(Object.new) : Object.new
356
- private_constant :NOT_GIVEN
357
-
358
- ##
359
- # Creates a new compiler for ERB. See ERB::Compiler.new for details
360
840
 
841
+ # :markup: markdown
842
+ #
843
+ # :call-seq:
844
+ # make_compiler -> erb_compiler
845
+ #
846
+ # Returns a new ERB::Compiler with the given `trim_mode`;
847
+ # for `trim_mode` values, see ERB.new:
848
+ #
849
+ # ```
850
+ # ERB.new('').make_compiler(nil)
851
+ # # => #<ERB::Compiler:0x000001cff9467678 @insert_cmd="print", @percent=false, @post_cmd=[], @pre_cmd=[], @put_cmd="print", @trim_mode=nil>
852
+ # ```
853
+ #
361
854
  def make_compiler(trim_mode)
362
855
  ERB::Compiler.new(trim_mode)
363
856
  end
364
857
 
365
- # The Ruby code generated by ERB
858
+ # :markup: markdown
859
+ #
860
+ # Returns the Ruby code that, when executed, generates the result;
861
+ # the code is executed by method #result,
862
+ # and by its wrapper methods #result_with_hash and #run:
863
+ #
864
+ # ```
865
+ # template = 'The time is <%= Time.now %>.'
866
+ # erb = ERB.new(template)
867
+ # erb.src
868
+ # # => "#coding:UTF-8\n_erbout = +''; _erbout.<< \"The time is \".freeze; _erbout.<<(( Time.now ).to_s); _erbout.<< \".\".freeze; _erbout"
869
+ # erb.result
870
+ # # => "The time is 2025-09-18 15:58:08 -0500."
871
+ # ```
872
+ #
873
+ # In a more readable format:
874
+ #
875
+ # ```
876
+ # # puts erb.src.split('; ')
877
+ # # #coding:UTF-8
878
+ # # _erbout = +''
879
+ # # _erbout.<< "The time is ".freeze
880
+ # # _erbout.<<(( Time.now ).to_s)
881
+ # # _erbout.<< ".".freeze
882
+ # # _erbout
883
+ # ```
884
+ #
885
+ # Variable `_erbout` is used to store the intermediate results in the code;
886
+ # the name `_erbout` is the default in ERB.new,
887
+ # and can be changed via keyword argument `eoutvar`:
888
+ #
889
+ # ```
890
+ # erb = ERB.new(template, eoutvar: '_foo')
891
+ # puts template.src.split('; ')
892
+ # #coding:UTF-8
893
+ # _foo = +''
894
+ # _foo.<< "The time is ".freeze
895
+ # _foo.<<(( Time.now ).to_s)
896
+ # _foo.<< ".".freeze
897
+ # _foo
898
+ # ```
899
+ #
366
900
  attr_reader :src
367
901
 
368
- # The encoding to eval
902
+ # :markup: markdown
903
+ #
904
+ # Returns the encoding of `self`;
905
+ # see [Encodings][encodings]:
906
+ #
907
+ # [encodings]: rdoc-ref:ERB@Encodings
908
+ #
369
909
  attr_reader :encoding
370
910
 
371
- # The optional _filename_ argument passed to Kernel#eval when the ERB code
372
- # is run
911
+ # :markup: markdown
912
+ #
913
+ # Sets or returns the file name to be used in reporting errors;
914
+ # see [Error Reporting][error reporting].
915
+ #
916
+ # [error reporting]: rdoc-ref:ERB@Error+Reporting
373
917
  attr_accessor :filename
374
918
 
375
- # The optional _lineno_ argument passed to Kernel#eval when the ERB code
376
- # is run
919
+ # :markup: markdown
920
+ #
921
+ # Sets or returns the line number to be used in reporting errors;
922
+ # see [Error Reporting][error reporting].
923
+ #
924
+ # [error reporting]: rdoc-ref:ERB@Error+Reporting
377
925
  attr_accessor :lineno
378
926
 
927
+ # :markup: markdown
379
928
  #
380
- # Sets optional filename and line number that will be used in ERB code
381
- # evaluation and error reporting. See also #filename= and #lineno=
382
- #
383
- # erb = ERB.new('<%= some_x %>')
384
- # erb.render
385
- # # undefined local variable or method `some_x'
386
- # # from (erb):1
929
+ # :call-seq:
930
+ # location = [filename, lineno] => [filename, lineno]
931
+ # location = filename -> filename
387
932
  #
388
- # erb.location = ['file.erb', 3]
389
- # # All subsequent error reporting would use new location
390
- # erb.render
391
- # # undefined local variable or method `some_x'
392
- # # from file.erb:4
933
+ # Sets the values of #filename and, if given, #lineno;
934
+ # see [Error Reporting][error reporting].
393
935
  #
936
+ # [error reporting]: rdoc-ref:ERB@Error+Reporting
394
937
  def location=((filename, lineno))
395
938
  @filename = filename
396
939
  @lineno = lineno if lineno
397
940
  end
398
941
 
942
+ # :markup: markdown
399
943
  #
400
- # Can be used to set _eoutvar_ as described in ERB::new. It's probably
401
- # easier to just use the constructor though, since calling this method
402
- # requires the setup of an ERB _compiler_ object.
944
+ # :call-seq:
945
+ # set_eoutvar(compiler, eoutvar = '_erbout') -> [eoutvar]
946
+ #
947
+ # Sets the `eoutvar` value in the ERB::Compiler object `compiler`;
948
+ # returns a 1-element array containing the value of `eoutvar`:
949
+ #
950
+ # ```
951
+ # template = ERB.new('')
952
+ # compiler = template.make_compiler(nil)
953
+ # pp compiler
954
+ # #<ERB::Compiler:0x000001cff8a9aa00
955
+ # @insert_cmd="print",
956
+ # @percent=false,
957
+ # @post_cmd=[],
958
+ # @pre_cmd=[],
959
+ # @put_cmd="print",
960
+ # @trim_mode=nil>
961
+ # template.set_eoutvar(compiler, '_foo') # => ["_foo"]
962
+ # pp compiler
963
+ # #<ERB::Compiler:0x000001cff8a9aa00
964
+ # @insert_cmd="_foo.<<",
965
+ # @percent=false,
966
+ # @post_cmd=["_foo"],
967
+ # @pre_cmd=["_foo = +''"],
968
+ # @put_cmd="_foo.<<",
969
+ # @trim_mode=nil>
970
+ # ```
403
971
  #
404
972
  def set_eoutvar(compiler, eoutvar = '_erbout')
405
973
  compiler.put_cmd = "#{eoutvar}.<<"
@@ -408,17 +976,34 @@ class ERB
408
976
  compiler.post_cmd = [eoutvar]
409
977
  end
410
978
 
411
- # Generate results and print them. (see ERB#result)
979
+ # :markup: markdown
980
+ #
981
+ # :call-seq:
982
+ # run(binding = new_toplevel) -> nil
983
+ #
984
+ # Like #result, but prints the result string (instead of returning it);
985
+ # returns `nil`.
412
986
  def run(b=new_toplevel)
413
987
  print self.result(b)
414
988
  end
415
989
 
990
+ # :markup: markdown
991
+ #
992
+ # :call-seq:
993
+ # result(binding = new_toplevel) -> new_string
994
+ #
995
+ # Returns the string result formed by processing \ERB tags found in the stored template in `self`.
996
+ #
997
+ # With no argument given, uses the default binding;
998
+ # see [Default Binding][default binding].
999
+ #
1000
+ # With argument `binding` given, uses the local binding;
1001
+ # see [Local Binding][local binding].
416
1002
  #
417
- # Executes the generated ERB code to produce a completed template, returning
418
- # the results of that code.
1003
+ # See also #result_with_hash.
419
1004
  #
420
- # _b_ accepts a Binding object which is used to set the context of
421
- # code evaluation.
1005
+ # [default binding]: rdoc-ref:ERB@Default+Binding
1006
+ # [local binding]: rdoc-ref:ERB@Local+Binding
422
1007
  #
423
1008
  def result(b=new_toplevel)
424
1009
  unless @_init.equal?(self.class.singleton_class)
@@ -427,8 +1012,18 @@ class ERB
427
1012
  eval(@src, b, (@filename || '(erb)'), @lineno)
428
1013
  end
429
1014
 
430
- # Render a template on a new toplevel binding with local variables specified
431
- # by a Hash object.
1015
+ # :markup: markdown
1016
+ #
1017
+ # :call-seq:
1018
+ # result_with_hash(hash) -> new_string
1019
+ #
1020
+ # Returns the string result formed by processing \ERB tags found in the stored string in `self`;
1021
+ # see [Augmented Binding][augmented binding].
1022
+ #
1023
+ # See also #result.
1024
+ #
1025
+ # [augmented binding]: rdoc-ref:ERB@Augmented+Binding
1026
+ #
432
1027
  def result_with_hash(hash)
433
1028
  b = new_toplevel(hash.keys)
434
1029
  hash.each_pair do |key, value|
@@ -437,10 +1032,22 @@ class ERB
437
1032
  result(b)
438
1033
  end
439
1034
 
440
- ##
441
- # Returns a new binding each time *near* TOPLEVEL_BINDING for runs that do
442
- # not specify a binding.
443
-
1035
+ # :markup: markdown
1036
+ #
1037
+ # :call-seq:
1038
+ # new_toplevel(symbols) -> new_binding
1039
+ #
1040
+ # Returns a new binding based on `TOPLEVEL_BINDING`;
1041
+ # used to create a default binding for a call to #result.
1042
+ #
1043
+ # See [Default Binding][default binding].
1044
+ #
1045
+ # Argument `symbols` is an array of symbols;
1046
+ # each symbol `symbol` is defined as a new variable to hide and
1047
+ # prevent it from overwriting a variable of the same name already
1048
+ # defined within the binding.
1049
+ #
1050
+ # [default binding]: rdoc-ref:ERB@Default+Binding
444
1051
  def new_toplevel(vars = nil)
445
1052
  b = TOPLEVEL_BINDING
446
1053
  if vars
@@ -453,13 +1060,31 @@ class ERB
453
1060
  end
454
1061
  private :new_toplevel
455
1062
 
456
- # Define _methodname_ as instance method of _mod_ from compiled Ruby source.
1063
+ # :markup: markdown
1064
+ #
1065
+ # :call-seq:
1066
+ # def_method(module, method_signature, filename = '(ERB)') -> method_name
1067
+ #
1068
+ # Creates and returns a new instance method in the given module `module`;
1069
+ # returns the method name as a symbol.
1070
+ #
1071
+ # The method is created from the given `method_signature`,
1072
+ # which consists of the method name and its argument names (if any).
1073
+ #
1074
+ # The `filename` sets the value of #filename;
1075
+ # see [Error Reporting][error reporting].
1076
+ #
1077
+ # [error reporting]: rdoc-ref:ERB@Error+Reporting
1078
+ #
1079
+ # ```
1080
+ # template = '<%= arg1 %> <%= arg2 %>'
1081
+ # erb = ERB.new(template)
1082
+ # MyModule = Module.new
1083
+ # erb.def_method(MyModule, 'render(arg1, arg2)') # => :render
1084
+ # class MyClass; include MyModule; end
1085
+ # MyClass.new.render('foo', 123) # => "foo 123"
1086
+ # ```
457
1087
  #
458
- # example:
459
- # filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
460
- # erb = ERB.new(File.read(filename))
461
- # erb.def_method(MyClass, 'render(arg1, arg2)', filename)
462
- # print MyClass.new.render('foo', 123)
463
1088
  def def_method(mod, methodname, fname='(ERB)')
464
1089
  src = self.src.sub(/^(?!#|$)/) {"def #{methodname}\n"} << "\nend\n"
465
1090
  mod.module_eval do
@@ -467,35 +1092,81 @@ class ERB
467
1092
  end
468
1093
  end
469
1094
 
470
- # Create unnamed module, define _methodname_ as instance method of it, and return it.
471
- #
472
- # example:
473
- # filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
474
- # erb = ERB.new(File.read(filename))
475
- # erb.filename = filename
476
- # MyModule = erb.def_module('render(arg1, arg2)')
477
- # class MyClass
478
- # include MyModule
479
- # end
1095
+ # :markup: markdown
1096
+ #
1097
+ # :call-seq:
1098
+ # def_module(method_name = 'erb') -> new_module
1099
+ #
1100
+ # Returns a new nameless module that has instance method `method_name`.
1101
+ #
1102
+ # ```
1103
+ # template = '<%= arg1 %> <%= arg2 %>'
1104
+ # erb = ERB.new(template)
1105
+ # MyModule = template.def_module('render(arg1, arg2)')
1106
+ # class MyClass
1107
+ # include MyModule
1108
+ # end
1109
+ # MyClass.new.render('foo', 123)
1110
+ # # => "foo 123"
1111
+ # ```
1112
+ #
480
1113
  def def_module(methodname='erb')
481
1114
  mod = Module.new
482
1115
  def_method(mod, methodname, @filename || '(ERB)')
483
1116
  mod
484
1117
  end
485
1118
 
486
- # Define unnamed class which has _methodname_ as instance method, and return it.
1119
+ # :markup: markdown
487
1120
  #
488
- # example:
489
- # class MyClass_
490
- # def initialize(arg1, arg2)
491
- # @arg1 = arg1; @arg2 = arg2
492
- # end
1121
+ # :call-seq:
1122
+ # def_class(super_class = Object, method_name = 'result') -> new_class
1123
+ #
1124
+ # Returns a new nameless class whose superclass is `super_class`,
1125
+ # and which has instance method `method_name`.
1126
+ #
1127
+ # Create a template from HTML that has embedded expression tags that use `@arg1` and `@arg2`:
1128
+ #
1129
+ # ```
1130
+ # html = <<TEMPLATE
1131
+ # <html>
1132
+ # <body>
1133
+ # <p><%= @arg1 %></p>
1134
+ # <p><%= @arg2 %></p>
1135
+ # </body>
1136
+ # </html>
1137
+ # TEMPLATE
1138
+ # template = ERB.new(html)
1139
+ # ```
1140
+ #
1141
+ # Create a base class that has `@arg1` and `@arg2`:
1142
+ #
1143
+ # ```
1144
+ # class MyBaseClass
1145
+ # def initialize(arg1, arg2)
1146
+ # @arg1 = arg1
1147
+ # @arg2 = arg2
493
1148
  # end
494
- # filename = 'example.rhtml' # @arg1 and @arg2 are used in example.rhtml
495
- # erb = ERB.new(File.read(filename))
496
- # erb.filename = filename
497
- # MyClass = erb.def_class(MyClass_, 'render()')
498
- # print MyClass.new('foo', 123).render()
1149
+ # end
1150
+ # ```
1151
+ #
1152
+ # Use method #def_class to create a subclass that has method `:render`:
1153
+ #
1154
+ # ```
1155
+ # MySubClass = template.def_class(MyBaseClass, :render)
1156
+ # ```
1157
+ #
1158
+ # Generate the result:
1159
+ #
1160
+ # ```
1161
+ # puts MySubClass.new('foo', 123).render
1162
+ # <html>
1163
+ # <body>
1164
+ # <p>foo</p>
1165
+ # <p>123</p>
1166
+ # </body>
1167
+ # </html>
1168
+ # ```
1169
+ #
499
1170
  def def_class(superklass=Object, methodname='result')
500
1171
  cls = Class.new(superklass)
501
1172
  def_method(cls, methodname, @filename || '(ERB)')