Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby/Rails: Reopening vs Overwriting a Class

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.classbefore 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.

like image 659
Mike Blyth Avatar asked Dec 16 '10 19:12

Mike Blyth


2 Answers

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.

like image 185
Chuck Avatar answered Nov 15 '22 16:11

Chuck


Use class_eval, that way you will be reopening the class the right way.
Here's a very good article on reopening classes.

like image 40
Mirko Avatar answered Nov 15 '22 16:11

Mirko