In Rails, how to add a new method to String class?

I want to build an index for different objects in my Rails project and would like to add a 'count_occurences' method that I can call on String objects.

I saw I could do something like

class String
  def self.count_occurences
    do_something_here
  end
end

What's the exact way to define this method, and where to put the code in my Rails project?

Thanks


You can define a new class in your application at lib/ext/string.rb and put this content in it:

class String
  def to_magic
    "magic"
  end
end

To load this class, you will need to require it in your config/application.rb file or in an initializer. If you had many of these extensions, an initializer is better! The way to load it is simple:

require 'ext/string'

The to_magic method will then be available on instances of the String class inside your application / console, i.e.:

>> "not magic".to_magic
=> "magic"

No plugins necessary.


I know this is an old thread, but it doesn't seem as if the accepted solution works in Rails 4+ (at least not for me). Putting the extension rb file in to config/initializers worked.

Alternatively, you can add /lib to the Rails autoloader (in config/application.rb, in the Application class:

config.autoload_paths += %W(#{config.root}/lib)

require 'ext/string'

See this: http://brettu.com/rails-ruby-tips-203-load-lib-files-in-rails-4/


When you want to extend some core class then you usually want to create a plugin (it is handy when need this code in another application). Here you can find a guide how to create a plugin http://guides.rubyonrails.org/plugins.html and point #3 show you how to extend String class: http://guides.rubyonrails.org/plugins.html#extending-core-classes