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

RubyRuby on-Rails-3Monkeypatching

Ruby Problem Overview


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

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

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/

Solution 3 - Ruby

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexView Question on Stackoverflow
Solution 1 - RubyRyan BiggView Answer on Stackoverflow
Solution 2 - RubyChristopher DaviesView Answer on Stackoverflow
Solution 3 - RubyIreneusz SkrobisView Answer on Stackoverflow