method_missing : le modèle mental du message sans réponse en Ruby method_missing: the mental model of the unanswered message in Ruby

Quand rien dans la chaîne d'ancêtres ne répond, Ruby appelle method_missing. Toujours avec son jumeau respond_to_missing?, sinon l'objet ment. Ruby 3.4.When nothing in the ancestor chain answers, Ruby calls method_missing. Always with its twin respond_to_missing?, or the object lies. Ruby 3.4.

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

En bref. Quand personne dans la chaîne d’ancêtres ne répond, Ruby appelle method_missing. Le redéfinir permet de répondre à ce qu’on n’a pas écrit, mais jamais seul.

Le modèle en une phrase

method_missing est le dernier maillon. Redéfinis-le toujours avec respond_to_missing?, et seulement pour un ensemble ouvert.

In short. When nobody in the ancestor chain answers, Ruby calls method_missing. Redefining it lets you answer what you never wrote, but never alone.

The model in one sentence

method_missing is the last link. Always redefine it with respond_to_missing?, and only for an open set.

f.dis_bonjour
f.respond_to?(:dis_bonjour)
f.truc
Au bout de la chaîneAt the end of the chain"dit bonjour""dit bonjour"classeObjectBasicObjectmethod_missingrespond_to_missing?hachuré gris = personne n'a répondugrey hatching = nobody answeredvérifié avec Ruby 3.4checked with Ruby 3.4
  1. f.dis_bonjour — Rien dans la chaîne ne répond : Ruby appelle method_missing, qui reconnaît le préfixe dis_.Nothing in the chain answers: Ruby calls method_missing, which recognises the dis_ prefix.
  2. f.respond_to?(:dis_bonjour) — Le jumeau respond_to_missing? dit la vérité : l'objet n'ment pas au duck typing.The twin respond_to_missing? tells the truth: the object doesn't lie to duck typing.
  3. f.truc — Message inconnu : on appelle super, et Ruby lève l'erreur habituelle.Unknown message: we call super, and Ruby raises the usual error.
Quand rien dans ancestors ne répond, Ruby appelle method_missing. Le redéfinir exige son jumeau respond_to_missing?, sinon l'objet ment à respond_to? et avale les fautes de frappe.When nothing in ancestors answers, Ruby calls method_missing. Redefining it requires its twin respond_to_missing?, otherwise the object lies to respond_to? and swallows typos.

La preuve, avec Ruby 3.4

class Fantome
  def method_missing(nom, *args)
    nom.to_s.start_with?("dis_") ? "dit #{nom.to_s.sub('dis_', '')}" : super
  end

  def respond_to_missing?(nom, priv = false)
    nom.to_s.start_with?("dis_") || super
  end
end

f = Fantome.new
p f.dis_bonjour                    # => "dit bonjour"
p f.respond_to?(:dis_bonjour)      # => true

L’erreur, telle que Ruby l’écrit

f.truc
undefined method 'truc' for an instance of Fantome (NoMethodError)

Le super rend l’erreur habituelle pour ce qu’on ne reconnaît pas.

Quand on oublie le jumeau

class Mal
  def method_missing(nom, *) = "avale #{nom}"
end

p Mal.new.nimporte                   # => "avale nimporte"
p Mal.new.respond_to?(:nimporte)     # => false
p Mal.new.tostring                   # => "avale tostring"

Ce que l’image cache

method_missing est lent à lire et à déboguer : la méthode n’existe nulle part dans le code. Si la liste des messages est connue, define_method génère de vraies méthodes, visibles et rapides.

Pour aller plus loin

Le numéro ci-dessous détaille method_missing, son jumeau et la limite de l’ensemble ouvert, avec des exercices.

The proof, with Ruby 3.4

class Fantome
  def method_missing(nom, *args)
    nom.to_s.start_with?("dis_") ? "dit #{nom.to_s.sub('dis_', '')}" : super
  end

  def respond_to_missing?(nom, priv = false)
    nom.to_s.start_with?("dis_") || super
  end
end

f = Fantome.new
p f.dis_bonjour                    # => "dit bonjour"
p f.respond_to?(:dis_bonjour)      # => true

The error, as Ruby writes it

f.truc
undefined method 'truc' for an instance of Fantome (NoMethodError)

The super gives the usual error for what you don’t recognise.

When you forget the twin

class Mal
  def method_missing(nom, *) = "avale #{nom}"
end

p Mal.new.nimporte                   # => "avale nimporte"
p Mal.new.respond_to?(:nimporte)     # => false
p Mal.new.tostring                   # => "avale tostring"

What the picture hides

method_missing is hard to read and debug: the method exists nowhere in the code. If the list of messages is known, define_method generates real methods, visible and fast.

Go deeper

The issue below details method_missing, its twin and the open-set limit, with exercises.

Questions fréquentesFrequently asked questions

Quand Ruby appelle-t-il method_missing ?When does Ruby call method_missing?

Quand il a parcouru toute la chaîne d'ancêtres sans trouver de méthode au nom demandé. Par défaut, elle lève NoMethodError.When it has walked the whole ancestor chain without finding a method with the requested name. By default it raises NoMethodError.

Pourquoi définir respond_to_missing? avec method_missing ?Why define respond_to_missing? alongside method_missing?

Sinon respond_to? répond false pour des messages que l'objet comprend : il ment au duck typing. Avec le jumeau, respond_to?(:dis_bonjour) vaut true.Otherwise respond_to? says false for messages the object understands: it lies to duck typing. With the twin, respond_to?(:dis_bonjour) is true.

Pourquoi appeler super dans method_missing ?Why call super in method_missing?

Pour les messages qu'on ne reconnaît pas : super relance le comportement normal et lève un vrai NoMethodError au lieu de les avaler.For messages you don't recognise: super restores the normal behaviour and raises a real NoMethodError instead of swallowing them.

Quel est le danger d'un method_missing qui répond à tout ?What's the danger of a method_missing that answers everything?

Les fautes de frappe disparaissent : Mal.new.tostring renvoie « avale tostring » au lieu de lever une erreur. Les bugs deviennent silencieux.Typos disappear: Mal.new.tostring returns “avale tostring” instead of raising. Bugs become silent.

Quand utiliser method_missing ?When should I use method_missing?

Pour un ensemble ouvert de messages, impossible à lister (proxy, DSL). Pour un ensemble connu, on génère les méthodes avec define_method.For an open set of messages that can't be listed (proxy, DSL). For a known set, generate the methods with define_method.

Rubymethod_missingrespond_to_missing?MétaprogrammationModèle mental

← Tous les articlesAll articles