Module: StrokeDB::Associations

Defined in:
lib/strokedb/document/dsl/associations.rb

Defined Under Namespace

Modules: HasManyAssociation

Instance Method Summary collapse

Instance Method Details

#has_many(slotname, opts = {}, &block) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/strokedb/document/dsl/associations.rb', line 36

def has_many(slotname, opts={}, &block)
  opts = opts.stringify_keys

  reference_slotname = opts['foreign_reference']
  through = opts['through'] || []
  through = [through] unless through.is_a?(Array)
  meta = (through.shift || slotname).to_s.singularize.camelize
  query = opts['conditions'] || {}

  extend_with = opts['extend'] || block

  @meta_initialization_procs << Proc.new do
    case extend_with
    when Proc
      extend_with_proc = extend_with
      extend_with = "HasMany#{slotname.to_s.camelize}"
      const_set(extend_with, Module.new(&extend_with_proc))
      extend_with = "#{self.name}::HasMany#{slotname.to_s.camelize}"
    when Module
      extend_with = extend_with.name
    when NilClass
    else
      raise "has_many extension should be either Module or Proc"
    end
    reference_slotname = reference_slotname || name.demodulize.tableize.singularize
    if name.index('::') # we're in namespaced meta
      _t = name.split('::')
      _t.pop
      _t << meta
      meta = _t.join('::') 
    end
    @args.last.reverse_merge!({"has_many_#{slotname}" => { :reference_slotname => reference_slotname, :through => through, :meta => meta, :query => query, :extend_with => extend_with } })
    define_method(slotname) do 
      _has_many_association(slotname,{})
    end

  end

end