define_method and small DSLs

define_method

define_method creates a real method from a block. Unlike method_missing, the method exists: methods lists it, respond_to? is true, and the editor can find it:

class A define_method(:x) { 1 } end p A.new.x p A.instance_methods(false)

ruby -e 'class A; define_method(:x) { 1 }; end; p A.new.x; p A.instance_methods(false)'

1 [:x]

The block is a closure, so it sees the variables around the definition. That is what lets a loop define a family of methods, each with its own value captured.

instance_variable_set

A method created from a name needs storage named from the same name. instance_variable_set and instance_variable_get take the @ name as a symbol or a string:

define_method("#{name}=") { |value| instance_variable_set("@#{name}", value) }

Reading uses instance_variable_get("@#{name}"). The pair is a hash with one slot per name, written where a reader of the class can see the name. A method that builds the name from user input is a code injection; build it from a list.

A class-level DSL

A class macro is a class method that defines instance methods. The setting method below is the whole pattern:

class Settings def self.setting(name, default:) define_method(name) { instance_variable_get("@#{name}") || default } define_method("#{name}=") { |value| instance_variable_set("@#{name}", value) } end setting :host, default: "localhost" setting :port, default: 3000 end settings = Settings.new p settings.host settings.port = 4000 p settings.port p Settings.instance_methods(false).sort

Two calls, four methods, and the defaults live next to the names. That is the DSL a configuration class, a serialiser or a test factory uses before it needs a framework.

Running it

ruby dsl.rb

"localhost" 4000 [:host, :host=, :port, :port=]

The default answers until a writer sets a value; the writer returns the value it stored, which is Ruby's assignment rule, not a choice. The list of instance methods, sorted so the output is stable, is the proof that the names are real.

What to watch for

A DSL that reads as English is easy to write and hard to debug. Keep the macros few, give them a plain method underneath, and let the macro call that method; a stack trace that names define_method for every frame is a day lost.

define_method is slower to call than a def in old Rubies and about the same in modern ones. The reason to choose it is that the name is data, not speed.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does this program print? class A define_method(:x) { 1 } end p A.new.x p A.instance_methods(false)

    Answer

    1 / [:x]

    The block becomes a real method, so the call returns 1 and the method list contains it.

  2. What does this program print? class A def store(name, value) instance_variable_set("@#{name}", value) end def read(name) instance_variable_get("@#{name}") end end a = A.new a.store("color", "red") puts a.read("color")

    Answer

    red

    The setter writes the instance variable whose name is built from the argument, and the getter reads the same one.

  3. What does this program print? class Settings def self.setting(name, default:) define_method(name) { instance_variable_get("@#{name}") || default } define_method("#{name}=") { |value| instance_variable_set("@#{name}", value) } end setting :host, default: "localhost" setting :port, default: 3000 end s = Settings.new puts s.host s.port = 4000 puts s.port

    Answer

    localhost / 4000

    The reader falls back to the default until the writer stores a value, and the stored port then wins.

  4. What does this program print? class A define_method("double") { |n| n * 2 } end puts A.new.double(21)

    Answer

    42

    The block is the method body, so the argument it receives is doubled.

  5. Why does define_method produce a method that tools can see, unlike method_missing?

    Answer

    It writes the method into the class, so methods and respond_to? know it

    A real method is in the class and appears in the method list, while a method_missing name is invisible until called.

  6. What does a block passed to define_method capture?

    Answer

    The variables around the definition, which is why a loop can build a family of methods

    The closure is what lets each generated method keep the value of its own iteration.

  7. Why is a method name built from user input a code injection risk?

    Answer

    The name could define or reach a method the program never intended

    The page says to build the name from a fixed list, so the caller cannot choose what the class defines.

  8. What does instance_variable_set("@#{name}", value) need in its first argument?

    Answer

    The instance variable name including the @ and as a string or a symbol

    The API takes the @ name, which is why the DSL builds it from the setting name.

  9. What is the page's advice for a DSL that reads as English?

    Answer

    Keep the macros few, give them a plain method underneath, and let the macro call it

    A plain method is what a stack trace and a reader can follow, and the macro stays a thin layer over it.

  10. Why choose define_method over def if the speed is about the same?

    Answer

    Because the method name is data that the program computes

    The reason is a name the program does not know until it runs, not performance.

Article author: Arthur Isaev