RbRuby
AdvancedLesson 15 of 16

Metaprogramming & DSLs – Ruby

method_missing, define_method, open classes, refinements and self-built DSLs.

In Ruby, code can create or intercept new methods at runtime. This is how frameworks like Rails (has_many, validates) come about. method_missing is called when a method does not exist – always implement it together with respond_to_missing?.

class Konfig
  def initialize
    @werte = {}
  end

  def method_missing(name, *args)
    n = name.to_s
    if n.end_with?("=")
      @werte[n.chomp("=").to_sym] = args.first
    elsif @werte.key?(name)
      @werte[name]
    else
      super
    end
  end

  def respond_to_missing?(name, include_private = false)
    name.to_s.end_with?("=") || @werte.key?(name) || super
  end
end

k = Konfig.new
k.port = 8080
puts k.port                  # 8080
puts k.respond_to?(:port)    # true
puts k.respond_to?(:host)    # false
begin
  k.host
rescue NoMethodError
  puts "NoMethodError"
end

define_method creates methods in a loop, send/public_send calls them by name:

class Nutzer
  ROLLEN = %i[admin editor gast]

  def initialize(rolle)
    @rolle = rolle
  end

  ROLLEN.each do |r|
    define_method("#{r}?") { @rolle == r }
  end
end

puts Nutzer.new(:admin).admin?               # true
puts Nutzer.new(:gast).editor?               # false
puts Nutzer.new(:editor).public_send(:editor?)
puts "abc".send(:upcase), 5.respond_to?(:+)
puts Nutzer.instance_methods(false).sort.inspect   # [:admin?, :editor?, :gast?]

Classes are open (monkey patching). Safer are refinements, which only apply where you call using:

class String
  def kurz(n = 10)
    length > n ? "#{self[0, n - 1]}…" : self
  end
end
puts "Ein sehr langer Satz".kurz(8)     # Ein seh…

module Hilfen
  refine Integer do
    def euro
      format("%.2f EUR", self)
    end
  end
end

using Hilfen
puts 5.euro                              # 5.00 EUR

With instance_eval and blocks you build a DSL (domain-specific language) in which the block runs in the context of an object:

class HtmlBauer
  def self.bauen(&block)
    b = new
    b.instance_eval(&block)
    b.to_s
  end

  def initialize
    @teile = []
  end

  %i[h1 p li].each do |tag|
    define_method(tag) { |text| @teile << "<#{tag}>#{text}</#{tag}>" }
  end

  def to_s
    @teile.join("\n")
  end
end

puts HtmlBauer.bauen {
  h1 "Titel"
  p "Text"
}
WarningMetaprogramming makes code hard to read, hard to debug and (with method_missing) slow. Use it sparingly and only when it really eliminates repetition. And test monkey patches: an update can break them.
TipKlasse.instance_methods(false), obj.methods - Object.instance_methods and obj.method(:name).source_location are good tools for exploring foreign code.