Where to override ActiveRecord

I want to reopen the ActiveRecord::Base class in a Rails environment
and is wondering about the best place to put the code. The new and
altered methods should be used by all instances in the whole Rails
application. Any ideas?

Thanks in advance

Erik L.

1 Like

Your app has a lib folder for this kind of stuff.

Any .rb files you put in lib will be automatically required. So if you
just
did

lib\active_record_patches.rb

module ActiveRecord
class Base
def self.foo
“hello world”
end
end

end

That should be it.

User.foo
=> “hello world”

1 Like

Thanks, just what I needed.

Regards

Erik

Great advice, one question:

Is this documented anywhere? None of my documentation seems to have
it.

fredistic

Great advice, one question:

Is this documented anywhere? None of my documentation seems to have
it.

fredistic

I’m trying this 13 years after (2020).

Is not working for me, Rails 6.0.2.1

Is there a new way of doing this?

Ok, I located that file in the initializers and it worked well.

I have a question on it why it has to be in initializers. I did try to have to methods for the Object class and have to add that file in initializer. Do you guys figure out any specific reason for it?

One not technical reason for putting them in the initializers is the purpose of the file.
Because overwriting ActiveRecord is a one time task, it make sense to put it there, I think.

But, for the technical reason, you could put the file not in the initializers itself, but you could locate a folder inside app and put it there, but you have to follow the rules of autoloading, in particular the rule of the naming of the files.

That rule was the main one that was forbidding me to put code in the app/lib or app/whatever folders: you have to match the name of the class with the name of the file and the name of a module with the name of a folder (now that I think about it, you are forced to write classes, like if Ruby was not already forcing you to write them anyways).

e.g: the following example would be autoloaded correctly:

# app/services/example/one.rb
module Example
  class One
  end
end

Files in the config/initializers folder are not tied to this rule but tied to the rules of initializers. That don’t know them 100%, except you have to stop spring (with spring stop) to reload the file if changed.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs