adding a method to built-in class in rails app

后端 未结 3 756
死守一世寂寞
死守一世寂寞 2020-12-24 07:51

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 t

3条回答
  •  暖寄归人
    2020-12-24 08:27

    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.

提交回复
热议问题