In my app I am having to interface with some 3rd party software I hope one day to replace. So, rather than keeping all the code that maps between my models’ data and the form it needs to be in for the 3rd party software in the models themselves, I’ve created a mapper module for each model, isolating the code somewhere that’s easy to delete when the time comes.
So I have something like the following:
app/
models/
people.rb
mappers/
people_mapper.rb
Ideally, I’d like to automatically include the modules in the model class with the matching name, the same way that helpers are automatically included in views of the same name. How/where are the helpers automatically included, and is this also the best place for me to add my own code?
you can try something like this :
then then
requireandincludethe module inActiveRecord::Basein an initializer (make sure that yourMappermodule requires all the files in your ‘mappers’ folder, or useconfig.autoload_paths).If you don’t want to use the
has_mappingclass method at all, you can try to overrideActiveRecord::Base‘sself.inheritedcallback, but it might become dangerous:I did not try any of this, so proceed with caution.
EDIT :
i was tired when i wrote this. there is a much simpler way to autoinclude the matching module :
initialize this with :
all inheriting class will now
include Mapper::Core, which will trigger inclusion of matching class.