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_missingest le dernier maillon. Redéfinis-le toujours avecrespond_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_missingis the last link. Always redefine it withrespond_to_missing?, and only for an open set.
f.dis_bonjourf.respond_to?(:dis_bonjour)f.truc
f.dis_bonjour— Rien dans la chaîne ne répond : Ruby appellemethod_missing, qui reconnaît le préfixedis_.Nothing in the chain answers: Ruby callsmethod_missing, which recognises thedis_prefix.f.respond_to?(:dis_bonjour)— Le jumeaurespond_to_missing?dit la vérité : l'objet n'ment pas au duck typing.The twinrespond_to_missing?tells the truth: the object doesn't lie to duck typing.f.truc— Message inconnu : on appellesuper, et Ruby lève l'erreur habituelle.Unknown message: we callsuper, and Ruby raises the usual error.
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) # => trueL’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) # => trueThe 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.