Class: Upgrow::BasicModel
- Inherits:
-
ImmutableObject
- Object
- ImmutableObject
- Upgrow::BasicModel
- Defined in:
- lib/upgrow/basic_model.rb
Overview
Base class for Models. As an Immutable Object, it sets a default schema with the minimal attribute ID, as well as requires all attributes to be set upon initialization.
Direct Known Subclasses
Defined Under Namespace
Classes: AssociationNotLoadedError
Instance Attribute Summary collapse
-
#associations ⇒ Object
readonly
Returns the value of attribute associations.
Attributes inherited from ImmutableObject
Class Method Summary collapse
-
.belongs_to(name) ⇒ Object
Defines an association in the Model Schema.
-
.has_many(name) ⇒ Object
Defines an association in the Model Schema.
Instance Method Summary collapse
-
#initialize(**args) ⇒ BasicModel
constructor
Initializes a new Model with the given member values.
-
#to_h ⇒ Hash<Symbol, Object>
Returns a Hash representation of Model along with all loaded associations.
Methods inherited from ImmutableObject
Constructor Details
#initialize(**args) ⇒ BasicModel
Initializes a new Model with the given member values.
41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/upgrow/basic_model.rb', line 41 def initialize(**args) @associations = self.class.schema.association_names.to_h do |name| [name, args[name]] end.freeze attributes = self.class.schema.attribute_names.to_h do |name| [name, args.fetch(name)] end super(**attributes) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object (private)
66 67 68 69 70 71 72 73 |
# File 'lib/upgrow/basic_model.rb', line 66 def method_missing(name, *args, &block) return super unless associations.include?(name) associations[name] || raise( AssociationNotLoadedError, "Association #{name} not loaded for #{self.class.name}." ) end |
Instance Attribute Details
#associations ⇒ Object (readonly)
Returns the value of attribute associations.
33 34 35 |
# File 'lib/upgrow/basic_model.rb', line 33 def associations @associations end |
Class Method Details
.belongs_to(name) ⇒ Object
Defines an association in the Model Schema.
17 18 19 |
# File 'lib/upgrow/basic_model.rb', line 17 def belongs_to(name) schema.association(name) end |
.has_many(name) ⇒ Object
Defines an association in the Model Schema.
24 25 26 |
# File 'lib/upgrow/basic_model.rb', line 24 def has_many(name) schema.association(name) end |
Instance Method Details
#to_h ⇒ Hash<Symbol, Object>
Returns a Hash representation of Model along with all loaded associations.
57 58 59 60 61 62 |
# File 'lib/upgrow/basic_model.rb', line 57 def to_h associations_hash = associations.compact.transform_values do |models| models.respond_to?(:map) ? models.map(&:to_h) : models.to_h end attributes.merge(associations_hash) end |