Skip to content
instance method

ERB#def_class

(?::Class, ?::String) -> ::Class
def_class(super_class = Object, method_name = 'result') → new_class

Returns a new nameless class whose superclass is super_class, and which has instance method method_name.

Create a template from HTML that has embedded expression tags that use @arg1 and @arg2:

Example
html = <<TEMPLATE
<html>
<body>
  <p><%= @arg1 %></p>
  <p><%= @arg2 %></p>
</body>
</html>
TEMPLATE
template = ERB.new(html)

Create a base class that has @arg1 and @arg2:

Example
class MyBaseClass
  def initialize(arg1, arg2)
    @arg1 = arg1
    @arg2 = arg2
  end
end

Use method def_class to create a subclass that has method :render:

Example
MySubClass = template.def_class(MyBaseClass, :render)

Generate the result:

puts MySubClass.new('foo', 123).render
<html>
<body>
  <p>foo</p>
  <p>123</p>
</body>
</html>
See also .version #def_method .new #def_module also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0