Extending ActiveRecord::Base

So I have a function that I want all my models to have access to. I’ve
done some reading and looked for pages and they all say you can extend
ActiveRecord::Base, and then all your models will get the extra
function. “Easy” thinks I. I must be missing something.

Here is what I’ve tried:

In lib, I created an active_directory folder and then in there made a
base.rb file. The file looks like this:

class ActiveRecord::Base
def some_function(param)
do some stuff
end
end

Then, in /config/environment.rb I have require ‘active_record/base.rb’

Well, that blew up spectacularly, and I couldn’t get script/server to
run. So I renamed it DB/base.rb and changed the require to reflect
that. Now script/server runs, but when I try to call some_function from
one of my models, it complains that ‘method_missing’: undefined method
‘some_function’ for SomeModel:Class (NoMethodError).

I’ve tried doing this for base.rb instead:

module ActiveRecord
class Base
def some_function(param)
do some stuff
end
end
end

and it still complains.

I even tried the following for base.rb:

module ActiveRecordCommon
def some_function(param)
do some stuff
end
end

Then in the /config/environment.rb I did:

require ‘DB/base.rb’
class ActiveRecord::Base
include ActiveRecordCommon
end

And even THAT didn’t work.

I’m all out of ideas. All the examples I’ve seen have been like the
ones I’ve described here. I know I’m missing something simple, as that
tends to be the case. Could someone please point it out to me?

Thanks.

I’m no expert but my guess is that if you’re intending your method to
be a class method, then you need to prefix the method name with “self.”

–gw

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