I want to add a method to a Rails model, to be used in testing. If I do this
class Model
def something_new
do_something
end
end
in the Rails console or in a file loaded at run time, Model is overwritten rather than modified. If I put something like v = Model.class
before the lines above, the new method is successfully added to the existing class. Apparently the reference is needed to signal that an existing class is being re-opened.
On the other hand, one can add a method to, say, Fixnum without having to refer to it first. What is going on here, and what is the usual way to ensure that an existing class is re-opened and modified rather than being overwritten?
Thanks.
It sounds like you're not requiring the class before using it. When you write Model.class
and there is no Model class, Rails automagically brings in Model for you. If you just write class Model
, it just sees that as a class definition. Just doing require 'model'
should work.
Use class_eval
, that way you will be reopening the class the right way.
Here's a very good article on reopening classes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With