Module: ZTK::DSL::Core::Relations::HasMany::ClassMethods Private

Defined in:
lib/ztk/dsl/core/relations/has_many.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Author:

Instance Method Summary (collapse)

Instance Method Details

- (Object) has_many(key, options = {})

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

[View source]

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
# File 'lib/ztk/dsl/core/relations/has_many.rb', line 43

def has_many(key, options={})
  has_many_relations[key] = {
    :class_name => key.to_s.classify,
    :key => key
  }.merge(options)

  define_method(key) do |*args|
    if args.count == 0
      get_has_many_reference(key)
    else
      send("#{key}=", *args)
    end
  end

  define_method("#{key}=") do |value|
    set_has_many_reference(key, value)
  end

  define_method(key.to_s.singularize) do |id=nil, &block|
    options = self.class.has_many_relations[key]
    data = options[:class_name].constantize.new(id, &block)
    get_has_many_reference(key) << data

    klass = self.class.to_s.demodulize.singularize.downcase

    data.send("#{klass}=", self)
    data
  end
end