Search code examples
rubyruby-on-rails-3monkeypatching

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


Solution

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