Everything I read about monkey patching says to do something like this:
class String
def foo
#your special code
end
end
But I can't find any instructions on where to put this code. In a rails app, can I just put this any crazy place I want? In a Module? A Model?
Do I need to include something in the file where I define my monkeypatch? Do I need to include my monkeypatch everywhere where I want to use it?
There is no set rule on this. Technically you can open it (the class; and add your method) anywhere. I usually make a special file called monkey_patches.rb
and put it in config/initializers
or in a misc
folder in my Rails app so if theres ever a conflict I know where to look.
Also I'd advise to use a Module
to wrap the monkey patch. Check out 3 ways to monkey patch without making a mess for more info.
His example:
module CoreExtensions
module DateTime
module BusinessDays
def weekday?
!sunday? && !saturday?
end
end
end
end
DateTime.include CoreExtensions::DateTime::BusinessDays