define_method : le modèle mental de la magie qu'on peut retrouver en Ruby define_method: the mental model of magic you can find again in Ruby

define_method crée de vraies méthodes, listées et trouvables, là où method_missing se contente d'intercepter. attr_accessor n'est que cette boucle. Ruby 3.4.define_method creates real, listed and findable methods, where method_missing merely intercepts. attr_accessor is just this loop. Ruby 3.4.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
MétaprogrammationMetaprogramming
PubliéPublished

En bref. Pour répondre à des noms qu’on n’a pas écrits, on peut intercepter (method_missing) ou générer (define_method). Générer laisse des traces : les méthodes existent vraiment.

Le modèle en une phrase

Générer, c’est définir de vraies méthodes : on les liste, on les teste, on les retrouve. Intercepter, c’est les simuler.

In short. To answer names you never wrote, you can intercept (method_missing) or generate (define_method). Generating leaves traces: the methods really exist.

The model in one sentence

Generating means defining real methods: you list them, test them, find them. Intercepting means simulating them.

"ouvert" → define_method("ouvert?")
"ferme", "archive" → define_method
s.respond_to?(:archive?)
Statut.instance_methods(false)Statut.instance_methods(false)1 méthode1 méthode:ouvert?:ferme?:archive?[ ] — rien à lister, rien à grepper[ ] — nothing to list, nothing to grepchaque tour de boucle définit une vraie méthodeeach loop pass defines a real methodvérifié avec Ruby 3.4checked with Ruby 3.4
  1. "ouvert" → define_method("ouvert?") — Premier tour de boucle : une vraie méthode apparaît.First loop pass: a real method appears.
  2. "ferme", "archive" → define_method — Trois tours, trois méthodes, listées dans instance_methods.Three passes, three methods, listed in instance_methods.
  3. s.respond_to?(:archive?) — respond_to? dit vrai, sans astuce : la méthode existe, un grep la retrouve.respond_to? says true, no trick needed: the method exists, a grep finds it.
define_method crée de vraies méthodes à partir d'un nom calculé : listées, vues par respond_to?, trouvées par grep. attr_accessor n'est que cette boucle.define_method creates real methods from a computed name: listed, seen by respond_to?, found by grep. attr_accessor is just this loop.

La preuve, avec Ruby 3.4

class Statut
  %w[ouvert ferme archive].each do |nom|
    define_method("#{nom}?") { @etat == nom }
  end
  def initialize(e) = @etat = e
end

s = Statut.new("ouvert")
p s.ouvert?, s.ferme?                  # => true, false
p s.respond_to?(:archive?)             # => true
p Statut.instance_methods(false).sort  # => [:archive?, :ferme?, :ouvert?]

attr_accessor n’est que cette boucle

class Pt
  attr_accessor :x
end
p Pt.instance_methods(false).sort   # => [:x, :x=]

La version écrite à la main :

class Pt2
  [:x].each do |n|
    define_method(n) { instance_variable_get("@#{n}") }
    define_method("#{n}=") { |v| instance_variable_set("@#{n}", v) }
  end
end

Ce que l’image cache

Générer n’est pas toujours mieux. Pour trois méthodes distinctes, trois def se lisent d’un coup d’œil. Génère quand les noms sont des données ou trop nombreux pour être écrits.

Pour aller plus loin

Le numéro ci-dessous détaille la génération de méthodes et ses limites, avec des exercices.

The proof, with Ruby 3.4

class Statut
  %w[ouvert ferme archive].each do |nom|
    define_method("#{nom}?") { @etat == nom }
  end
  def initialize(e) = @etat = e
end

s = Statut.new("ouvert")
p s.ouvert?, s.ferme?                  # => true, false
p s.respond_to?(:archive?)             # => true
p Statut.instance_methods(false).sort  # => [:archive?, :ferme?, :ouvert?]

attr_accessor is just this loop

class Pt
  attr_accessor :x
end
p Pt.instance_methods(false).sort   # => [:x, :x=]

The hand-written version:

class Pt2
  [:x].each do |n|
    define_method(n) { instance_variable_get("@#{n}") }
    define_method("#{n}=") { |v| instance_variable_set("@#{n}", v) }
  end
end

What the picture hides

Generating isn’t always better. For three distinct methods, three def read at a glance. Generate when names are data or too many to write out.

Go deeper

The issue below details method generation and its limits, with exercises.

Questions fréquentesFrequently asked questions

Que fait define_method ?What does define_method do?

Il crée une vraie méthode d'instance à partir d'un nom calculé et d'un bloc : define_method("ouvert?") { … }. Elle apparaît dans instance_methods.It creates a real instance method from a computed name and a block: define_method("ouvert?") { … }. It shows up in instance_methods.

Quelle différence avec method_missing ?How is it different from method_missing?

method_missing intercepte à l'exécution sans rien définir ; define_method définit la méthode, donc respond_to? et grep la voient.method_missing intercepts at runtime without defining anything; define_method defines the method, so respond_to? and grep see it.

Qu'est-ce que attr_accessor fait vraiment ?What does attr_accessor really do?

Il définit deux méthodes, x et x=, comme une boucle de define_method autour de instance_variable_get et instance_variable_set.It defines two methods, x and x=, like a define_method loop around instance_variable_get and instance_variable_set.

Quand générer plutôt qu'écrire avec def ?When should I generate rather than write with def?

Quand les noms sont des données ou nombreux (statuts, champs). Pour trois méthodes différentes, def est plus lisible et gagne.When names are data or numerous (statuses, fields). For three different methods, def is more readable and wins.

Comment vérifier les méthodes générées ?How do I check the generated methods?

Avec Statut.instance_methods(false), qui donne [:archive?, :ferme?, :ouvert?], et respond_to? sur une instance.With Statut.instance_methods(false), which gives [:archive?, :ferme?, :ouvert?], and respond_to? on an instance.

Rubydefine_methodMétaprogrammationattr_accessorModèle mental

← Tous les articlesAll articles