En bref. Une classe Ruby n’est jamais fermée : on peut rouvrir String. Mais il n’y a qu’une String, donc rouvrir agit sur tout le programme.
Le modèle en une phrase
Un patch doit-il être visible partout (monkey-patch) ou seulement dans mon fichier (refinement) ? Souvent, pas de patch du tout.
In short. A Ruby class is never closed: you can reopen String. But there is only one String, so reopening acts on the whole program.
The model in one sentence
Should a patch be visible everywhere (monkey-patch) or only in my file (refinement)? Often, no patch at all.
class String; def crier = upcase + "!"; end"salut".crier # dans mon code"salut".crier # dans une gem
class String; def crier = upcase + "!"; end— On rouvreString. Il n'en existe qu'une : le changement est global.We reopenString. There is only one: the change is global."salut".crier # dans mon code— Mon code voit la nouvelle méthode, comme prévu.My code sees the new method, as expected."salut".crier # dans une gem— Mais la gem la voit aussi, et pourrait avoir défini la sienne : action à distance.But the gem sees it too, and might have defined its own: action at a distance.
La preuve, avec Ruby 3.4
class String
def crier = upcase + "!"
end
p "salut".crier # => "SALUT!"N’importe quel code du programme, gems comprises, peut maintenant appeler crier.
Le refinement, limité au fichier
module Doux
refine String do
def murmurer = downcase + "..."
end
end
"SALUT".murmurer # NoMethodError, pas encore activé
using Doux
p "SALUT".murmurer # => "salut..."L’erreur, telle que Ruby l’écrit
"SALUT".murmurer
undefined method 'murmurer' for an instance of String (NoMethodError)Ce que l’image cache
Un refinement n’est pas un monkey-patch en plus sûr à tout faire : sa portée, lexicale, surprend, et il n’agit pas partout (par exemple avec certains appels dynamiques). Avant de patcher, demande-toi si une fonction ou une petite classe ne suffit pas.
Pour aller plus loin
Le numéro ci-dessous détaille les classes ouvertes, la portée du monkey-patch et les refinements, avec des exercices.
The proof, with Ruby 3.4
class String
def crier = upcase + "!"
end
p "salut".crier # => "SALUT!"Any code in the program, gems included, can now call crier.
The refinement, limited to the file
module Doux
refine String do
def murmurer = downcase + "..."
end
end
"SALUT".murmurer # NoMethodError, not activated yet
using Doux
p "SALUT".murmurer # => "salut..."The error, as Ruby writes it
"SALUT".murmurer
undefined method 'murmurer' for an instance of String (NoMethodError)What the picture hides
A refinement isn’t a safer monkey-patch for everything: its lexical scope surprises, and it doesn’t act everywhere (for instance with some dynamic calls). Before patching, ask whether a function or a small class wouldn’t do.
Go deeper
The issue below details open classes, the scope of a monkey-patch and refinements, with exercises.