Module: Historical::MongoMapperEnhancements
- Included in:
- Historical::Models::AttributeDiff, Historical::Models::ModelVersion, Historical::Models::ModelVersion::Diff, Historical::Models::ModelVersion::Meta
- Defined in:
- lib/historical/mongo_mapper_enhancements.rb
Overview
Contains some helper methods for better MongoMapper integration.
Instance Method Summary collapse
-
#belongs_to_active_record(name, options = {}) ⇒ Object
Simple ‘belongs_to` relation to an ActiveRecord model.
Instance Method Details
#belongs_to_active_record(name, options = {}) ⇒ Object
Simple ‘belongs_to` relation to an ActiveRecord model.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/historical/mongo_mapper_enhancements.rb', line 10 def belongs_to_active_record(name, = {}) ar_id_field = "#{name}_id" ar_type_field = "#{name}_type" polymorphic = .delete(:polymorphic) class_name = .delete(:class_name) model_class = nil # classname unless polymorphic if class_name model_class = class_name.is_a?(Class) ? class_name.name : class_name.classify else model_class = name.to_s.classify end end # define the keys key ar_id_field, Integer, key ar_type_field, String, if polymorphic # getter define_method name do if id = send(ar_id_field) if polymorphic type_class = send(ar_type_field) type_class ? type_class.constantize.find(id) : nil else model_class.constantize.find(id) end else nil end end # setter define_method "#{name}=" do |val| id = type = nil if val raise "expected an instace of ActiveRecord::Base, got: #{val.class.name}" unless val.is_a?(::ActiveRecord::Base) type = val.class.name id = val.id end send("#{ar_id_field}=", id) send("#{ar_type_field}=", type) if polymorphic end end |