开发者

Ruby/Rails: Reopening vs Overwriting a Class

开发者 https://www.devze.com 2023-01-31 12:39 出处:网络
I want to add a method to a Rails model, to be used in testing. If I do this class Model def something_new

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.


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.


Just as an addition to Chuck's answer here is the quote from Rails docs:

6.1.1 Constants after the class and module Keywords Ruby performs a lookup for the constant that follows a class or module keyword because it needs to know if the class or module is going to be created or reopened.

If the constant is not defined at that point it is not considered to be a missing constant, autoloading is not triggered.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号