Skip to content

Commit a082298

Browse files
BurdetteLamark0kubun
authored andcommitted
[DOC] Doc for #def_method and #def_module
1 parent 4ca7784 commit a082298

File tree

1 file changed

+42
-16
lines changed

1 file changed

+42
-16
lines changed

lib/erb.rb

Lines changed: 42 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1095,30 +1095,56 @@ def new_toplevel(vars = nil)
10951095
end
10961096
private :new_toplevel
10971097

1098-
# Define _methodname_ as instance method of _mod_ from compiled Ruby source.
1098+
# :markup: markdown
1099+
#
1100+
# :call-seq:
1101+
# def_method(module, method_signature, filename = '(ERB)') -> method_name
1102+
#
1103+
# Creates and returns a new instance method in the given module `module`;
1104+
# returns the method name as a symbol.
1105+
#
1106+
# The method is created from the given `method_signature`,
1107+
# which consists of the method name and its argument names (if any).
1108+
#
1109+
# The `filename` sets the value of #filename;
1110+
# see [Error Reporting][error reporting].
1111+
#
1112+
# [error reporting]: rdoc-ref:ERB@Error+Reporting
1113+
#
1114+
# ```
1115+
# s = '<%= arg1 %> <%= arg2 %>'
1116+
# template = ERB.new(s)
1117+
# MyModule = Module.new
1118+
# template.def_method(MyModule, 'render(arg1, arg2)') # => :render
1119+
# class MyClass; include MyModule; end
1120+
# MyClass.new.render('foo', 123) # => "foo 123"
1121+
# ```
10991122
#
1100-
# example:
1101-
# filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
1102-
# erb = ERB.new(File.read(filename))
1103-
# erb.def_method(MyClass, 'render(arg1, arg2)', filename)
1104-
# print MyClass.new.render('foo', 123)
11051123
def def_method(mod, methodname, fname='(ERB)')
11061124
src = self.src.sub(/^(?!#|$)/) {"def #{methodname}\n"} << "\nend\n"
11071125
mod.module_eval do
11081126
eval(src, binding, fname, -1)
11091127
end
11101128
end
11111129

1112-
# Create unnamed module, define _methodname_ as instance method of it, and return it.
1113-
#
1114-
# example:
1115-
# filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml
1116-
# erb = ERB.new(File.read(filename))
1117-
# erb.filename = filename
1118-
# MyModule = erb.def_module('render(arg1, arg2)')
1119-
# class MyClass
1120-
# include MyModule
1121-
# end
1130+
# :markup: markdown
1131+
#
1132+
# :call-seq:
1133+
# def_module(method_name = 'erb') -> new_module
1134+
#
1135+
# Returns a new nameless module that has instance method `method_name`.
1136+
#
1137+
# ```
1138+
# s = '<%= arg1 %> <%= arg2 %>'
1139+
# template = ERB.new(s)
1140+
# MyModule = template.def_module('render(arg1, arg2)')
1141+
# class MyClass
1142+
# include MyModule
1143+
# end
1144+
# MyClass.new.render('foo', 123)
1145+
# # => "foo 123"
1146+
# ```
1147+
#
11221148
def def_module(methodname='erb')
11231149
mod = Module.new
11241150
def_method(mod, methodname, @filename || '(ERB)')

0 commit comments

Comments
 (0)