Module: Sack::Database::Model::Relationships::ClassMethods
- Defined in:
- lib/sack/database/model/relationships.rb,
lib/sack/database/model/relationships/has_many.rb,
lib/sack/database/model/relationships/belongs_to.rb
Overview
Class Methods
Instance Method Summary collapse
-
#belongs_to(options) ⇒ Object
Belongs To: Defines the ‘slave’ end of any relationship (the one that holds the other entity’s ID).
-
#has_many(options) ⇒ Object
Has Many: Defines the ‘one’ side a one-to-many relationship.
-
#relationships ⇒ Object
Relationships: Gets the relationships for the Model.
Instance Method Details
#belongs_to(options) ⇒ Object
Belongs To: Defines the ‘slave’ end of any relationship (the one that holds the other entity’s ID).
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 |
# File 'lib/sack/database/model/relationships/belongs_to.rb', line 22 def belongs_to # Check Options if .is_a? Hash # Internalise Options (so we can mess it up) = .clone # Pull Relationship Name & Target Model name, target_model_name = .first .delete name else # Acquire everything from just a Symbol name = target_model_name = name end # Construct Proxy Method Module proxy = Module.new do # Proxy Method for Relationship: # Allows fetching entities for a given belongs-to relationship. define_method name do |db, data| # Find Target Model target_model = @model_root.const_get target_model_name.to_s.camelcase # Fetch Relationship Entity target_model.find db, data[name] end end # Extend Model with Proxy @model.extend proxy end |
#has_many(options) ⇒ Object
Has Many: Defines the ‘one’ side a one-to-many relationship.
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 |
# File 'lib/sack/database/model/relationships/has_many.rb', line 22 def has_many # Internalise Options (so we can mess it up) = .dclone # Pull Relationship Name & Target Model name, target_model_name = .first .delete name # Determine Foreign Key (which field in the remote model holds our ID) foreign_key = [:fk] || table_name # Register Relationship relationships[name] = { target: target_model_name, fk: foreign_key, options: .dclone } # Construct Proxy Method Module proxy = Module.new do # Proxy Method for Relationship: # Allows fetching entities for a given has-many relationship. define_method name do |db, data| # Find Target Model target_model = @model_root.const_get target_model_name.to_s.camelcase # Fetch Relationship Entities target_model.fetch_by db, foreign_key, data[:id] end end # Extend Model with Proxy @model.extend proxy end |
#relationships ⇒ Object
Relationships: Gets the relationships for the Model.
34 35 36 |
# File 'lib/sack/database/model/relationships.rb', line 34 def relationships @relationships ||= {} end |