Backo
Backo

Reputation: 18871

Extending classes with new methods

I am using Ruby on Rails 3.0.9 and I would like to know what is the best approach\choice to extend my classes with new methods. I am planning to implement new methods for editing stings to perform action as made by the module ActiveSupport::Inflector.

I thought to create a new file for that in the lib folder... then, how I should include that file to make it possible to call those methods in my controllers and models?

Upvotes: 0

Views: 251

Answers (1)

apneadiving
apneadiving

Reputation: 115511

If you are only adding methods to the String class, monkey_patch it in a file within /lib:

class String

  def my_method
  end

end

But if you want to add other methods to a class:

  • create a module

  • create the methods in the module

  • include the module in your class (it's a mixin)

Upvotes: 1

Related Questions