Fellow Stranger
Fellow Stranger

Reputation: 34013

Add method to the String class in a Rails app

I want to add a method for possessive strings with the following code:

module PossessiveHelper
  def possessive
    suffix = if self.downcase == 'it'
      "s"
    elsif self.downcase == 'who'
      'se'
    elsif self.end_with?('s')
      "'"
    else
      "'s"
    end
    self + suffix
  end
end

class String
  include Possessive
end

I wonder though where and how I'm including this in a Rails app 3.2?

Upvotes: 0

Views: 374

Answers (2)

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

I like to have an initializer called monkey_patching.rb with the following:

Dir[Rails.root.join('lib', 'monkey_patching', '**', '*.rb')].each do |file|
  require file.to_s
end

Then all you have to do is to add your code in a lib/monkey_patching/string.rb

Upvotes: 2

Amit Thawait
Amit Thawait

Reputation: 5292

You should create a rb file with the same content and put it in config/initializers.

It will get loaded during initialization of your Rails application and these new methods will be available for all string objects.

Upvotes: 1

Related Questions