21

I want to add a method to the Array class in a rails app. Where should I put this method?

EDIT to be clearer, obviously I put it in a file somewhere, but how do I tell the rails app about where to find it?

inglesp
  • 3,299
  • 9
  • 32
  • 30

3 Answers3

42

One way to do this is to create a file at lib/rails_extensions.rb. Then, add your extensions like so:

class Array
  def bring_me_food
    # ...
  end

  def make_tea
    # ...
  end
end

class Hash
  def rub_my_shoulders
    # ...
  end
end

Then in config/environment.rb, add this:

require 'rails_extensions'

Your mileage with subservient objects may vary.

Ron DeVera
  • 14,394
  • 6
  • 41
  • 36
  • 1
    That's what I was looking for, thanks. I found, however, that this only works when I put the require line at the bottom of config/environment.rb – inglesp Mar 24 '09 at 12:25
  • 3
    You're lucky to have such servient Hash's and Array's in your environment. – Eric H. Apr 28 '14 at 22:36
  • 1
    It's also worth to note that you may add your extensions in `config/initializers/rails_extensions.rb`. In that way, you don't have to add `require` in `environment.rb`. Tested in ruby 2.6.4 and rails 6. – Roshan Oct 09 '19 at 07:23
6

By default, when you call "require", Rails will look in (from the Rails edge source):

app app/metal app/models app/controllers app/helpers app/services lib vendor

For simplicity's sake, put the file in lib/, and require it by name in your config/environment.rb, or you can put it in config/initializers/array_extension.rb, and it'll be automatically loaded.

Where I work, we've put all of our extensions to the core Ruby library into a plugin, and stored it in (Rails.root/)vendor/plugins/utilities/lib/core_ext, and then we require the individual extensions in the plugin's init.rb.

Another way to skin this cat: if you say, want to store your core extensions in Rails.root/core_ext, then you can add that path as a load path in your configuration block in environment.rb:

Rails::Initializer.run do |config|
  config.load_paths << 'core_ext'
end

Then you can call "require 'array_extension'" from anywhere, and it'll load.

Colin Curtin
  • 2,093
  • 15
  • 17
0

Just put it in a new file, e.g. array_extended.rb

class Array

  def my_new_method()
    ...
  end

end

After that you may include this file with require "array_extended.rb". Be sure you don't override already existing methods as this may break other functionality.

Koraktor
  • 41,357
  • 10
  • 69
  • 99