开发者

Ruby: How do I add methods to Object? (or simply Extend the object class)

开发者 https://www.devze.com 2023-03-27 08:14 出处:网络
I want to extend Object to add a few methods. so I can do @object.table_name rather than @object.class.name.tableize

I want to extend Object to add a few methods.

so I can do @object.table_name rather than @object.class.name.tableize

and similar things like that.

I'm using Ruby 1.8.7 and Rails 2.3.8, so maybe 开发者_开发问答this sort of thing would go in the lib folder as a module? I don't know.


# object.rb
class Object
  def table_name
    self.class.name.tableize
  end
end

put it into /config/initializers or into lib folder (in this case you'll need to include it in ApplicationController).


An idiom you'll sometimes see for delegating instance methods to the class is just that:

delegate :table_name, :to => 'self'
0

精彩评论

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