zer0uno
zer0uno

Reputation: 8030

Extend the ActiveRecord::Base

If I make something like this:

class ActiveRecord::Base
  def self.encrypt(*attr_names)
    encrypter = Encrypter.new(attr_names)

    before_save encrypter
    after_save  encrypter
    after_find  encrypter

    define_method(:after_find) { }
  end
end
  1. Where do I have to save this file?
  2. Do it need to have a special name?
  3. Do I have to call require somewhere?
  4. Could I save it in the model folder?
  5. Is a class declared in the model folder visible from the other classes in the model folder without calling require?

Upvotes: 4

Views: 1698

Answers (1)

Cristian Bica
Cristian Bica

Reputation: 4117

  1. config/initializers/whatever.rb
  2. nope
  3. nope ... initializers are loaded on application boot
  4. nope
  5. Yup. Rails autoload will search for it.

The rails-ish way of doing what is you're trying to do is: create a file in lib/encryptable.rb (or app/models/concerns if you're on rails 4) which defines a module with your methods. Then in your models you can do include Encryptable or (for all models) in an initializer:

ActiveRecord::Base.class_eval do
  include Encryptable
end

read more about rails 4 concerns here: How to use concerns in Rails 4

Upvotes: 5

Related Questions