Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-plugins

How do I make a library function in a plugin that is accessible by everything in Rails 3?


I would like to create a plugin library function that can be used anywhere in my rails app. I'm sure this must be very easy to do but I can not seem to find examples on how to do this. All the tutorials I've found so far show how to only extend classes or make methods that only work inside model or controllers.

Even RailsGuide does not seem to show how to do this.

Hey thanks for the help!


Solution

  • The simplest way to do this is to create a module or class method and then call that. For example:

    module MySpecialModule
      def self.do_something
        puts 'hello world'
      end
    end
    

    Then, the following can be called from anywhere:

    MySpecialModule.do_something
    

    If you are really intent on having your do_something method be called from every single object in Ruby, then you can extend the object class like this:

    class Object
      def do_something
        puts 'hello world'
      end
    end
    
    class K
    end
    
    K.new.do_something
    => hello world
    

    You can use this same method to extend any base class, for example ActiveRecord::Base.