I’m in the process of writing an Importable concern for my rails project. This concern will provide a generic way for me to import a csv file into any model that includes Importable.
I need a way for each model to specify which field the import code should use to find existing records. Are there any recommended ways of adding this type of configuring for a concern?
Rather than including the concern in each model, I’d suggest creating an
ActiveRecordsubmodule and extendActiveRecord::Basewith it, and then add a method in that submodule (sayinclude_importable) that does the including. You can then pass the field name as an argument to that method, and in the method define an instance variable and accessor (say for exampleimportable_field) to save the field name for reference in yourImportableclass and instance methods.So something like this:
You’ll then need to extend
ActiveRecordwith this module, say by putting this line in an initializer (config/initializers/active_record.rb):(If the concern is in your
config.autoload_pathsthen you shouldn’t need to require it here, see the comments below.)Then in your models, you would include
Importablelike this:And the
imported_fieldreader will return the name of the field:In your
InstanceMethods, you can then set the value of the imported field in your instance methods by passing the name of the field towrite_attribute, and get the value usingread_attribute:Hope that helps. This is just my personal take on this, though, there are other ways to do it (and I’d be interested to hear about them too).