Module: Historical::MongoMapperEnhancements

Overview

Contains some helper methods for better MongoMapper integration.

Instance Method Summary collapse

Instance Method Details

#belongs_to_active_record(name, options = {}) ⇒ Object

Simple ‘belongs_to` relation to an ActiveRecord model.

Parameters:

  • name

    The name of the relation.

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :class_name (String) — default: name.classify

    The class name of the model (if it can’t be guessed from the name)

  • :polymorphic (true, false) — default: false

    Will create an additional name_type key in the 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, options = {})
  ar_id_field   = "#{name}_id"
  ar_type_field = "#{name}_type"
  
  polymorphic   = options.delete(:polymorphic)
  class_name    = options.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,  options
  key ar_type_field,  String,   options 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