I’m developing a ruby on rails app and I want to be able to excecute a method on every AR object before each save.
I thought I’d create a layer-super-type like this:
MyObject << DomainObject << ActiveRecord::Base
and put in DomainObject a callback (before_save) with my special method (which basically strips all tags like ‘H1’ from the string attributes of the object).
The catch is that rails is asking for the domain_object table, which I obviously don’t have.
My second attempt was to monkeypatch active record, like this:
module ActiveRecord class Base def my_method .... end end end
And put that under the lib folder.
This doesnt work, it tells me that my_method is undefined.
Any ideas?
Try using an abstract class for your domain object.
With an abstract class, you are creating a model which cannot have objects (cannot be instantiated) and don’t have an associated table.
From reading Rails: Where to put the ‘other’ files from Strictly Untyped,
so placing the file in the lib folder, it will not be run when Rails starts and won’t monkey patch ActiveRecord::Base. You could place the file in
config/initializers, but I think there are better alternatives.