Search code examples
ruby-on-railsrubymonkeypatching

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


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.


Solution

  • # 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).