Module: Cistern::Associations
- Defined in:
- lib/cistern/associations.rb
Class Method Summary collapse
Instance Method Summary collapse
-
#associations ⇒ Hash{Symbol=>Array}
Lists the associations defined on the resource.
-
#belongs_to(name, *args, &block) ⇒ Cistern::Model
Define an assocation that references a model.
-
#has_many(name, *args, &block) ⇒ Cistern::Collection
Define an assocation that references a collection.
Class Method Details
.extended(klass) ⇒ Object
4 5 6 7 8 9 10 11 12 |
# File 'lib/cistern/associations.rb', line 4 def self.extended(klass) def klass. @association_overlay ||= const_set(:Associations, Module.new) end klass.send(:include, klass.) super end |
Instance Method Details
#associations ⇒ Hash{Symbol=>Array}
Lists the associations defined on the resource
16 17 18 |
# File 'lib/cistern/associations.rb', line 16 def associations @associations ||= Hash.new { |h,k| h[k] = [] } end |
#belongs_to(name, *args, &block) ⇒ Cistern::Model
Define an assocation that references a model.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/cistern/associations.rb', line 71 def belongs_to(name, *args, &block) name_sym = name.to_sym reader_method = name writer_method = "#{name}=" = args.last.is_a?(::Hash) ? args.pop : {} scope = args.first || block attribute name_sym, .merge(writer: false, reader: false) .module_eval do define_method reader_method do model = instance_exec(&scope) attributes[name_sym] = model.attributes model end end .module_eval do define_method writer_method do |model| data = model.respond_to?(:attributes) ? model.attributes : model attributes[name_sym] = data model end end associations[:belongs_to] << name_sym end |
#has_many(name, *args, &block) ⇒ Cistern::Collection
Define an assocation that references a collection.
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 59 60 |
# File 'lib/cistern/associations.rb', line 30 def has_many(name, *args, &block) name_sym = name.to_sym reader_method = name writer_method = "#{name}=" = args.last.is_a?(::Hash) ? args.pop : {} scope = args.first || block attribute name_sym, .merge(writer: false, reader: false, type: :array) .module_eval do define_method reader_method do collection = instance_exec(&scope) records = attributes[name_sym] || [] collection.load(records) if records.any? collection end end .module_eval do define_method writer_method do |models| attributes[name] = Array(models).map do |model| model.respond_to?(:attributes) ? model.attributes : model end end end associations[:has_many] << name_sym end |