Module: Cistern::Associations
- Defined in:
- lib/cistern/associations.rb
Instance Method Summary collapse
-
#associations ⇒ Hash{Symbol=>Array}
Lists the associations defined on the resource.
-
#belongs_to(name, block) ⇒ Cistern::Model
Define an assocation that references a model.
-
#has_many(name, scope) ⇒ Cistern::Collection
Define an assocation that references a collection.
Instance Method Details
#associations ⇒ Hash{Symbol=>Array}
Lists the associations defined on the resource
6 7 8 |
# File 'lib/cistern/associations.rb', line 6 def associations @associations ||= Hash.new { |h,k| h[k] = [] } end |
#belongs_to(name, block) ⇒ Cistern::Model
Define an assocation that references a model.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/cistern/associations.rb', line 54 def belongs_to(name, block) name_sym = name.to_sym reader_method = name writer_method = "#{name}=" attribute name_sym define_method reader_method do model = instance_exec(&block) attributes[name_sym] = model.attributes model end define_method writer_method do |model| data = model.respond_to?(:attributes) ? model.attributes : model attributes[name_sym] = data model end associations[:belongs_to] << name_sym end |
#has_many(name, scope) ⇒ Cistern::Collection
Define an assocation that references a collection.
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/cistern/associations.rb', line 20 def has_many(name, scope) name_sym = name.to_sym reader_method = name writer_method = "#{name}=" attribute name, type: :array define_method reader_method do collection = instance_exec(&scope) records = attributes[name_sym] || [] collection.load(records) if records.any? collection end define_method writer_method do |models| attributes[name] = Array(models).map do |model| model.respond_to?(:attributes) ? model.attributes : model end end associations[:has_many] << name_sym end |