Class: Upgrow::BasicModel

Inherits:
ImmutableObject show all
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

Model

Defined Under Namespace

Classes: AssociationNotLoadedError

Instance Attribute Summary collapse

Attributes inherited from ImmutableObject

#attributes

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ImmutableObject

attribute

Constructor Details

#initialize(**args) ⇒ BasicModel

Initializes a new Model with the given member values.

Parameters:

  • args (Hash<Symbol, Object>)

    the list of values for each attribute and association.

Raises:

  • (KeyError)

    if an attribute is missing in the list of arguments.



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

#associationsObject (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.

Parameters:

  • name (Symbol)

    the name of the association.



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.

Parameters:

  • name (Symbol)

    the name of the association.



24
25
26
# File 'lib/upgrow/basic_model.rb', line 24

def has_many(name)
  schema.association(name)
end

Instance Method Details

#to_hHash<Symbol, Object>

Returns a Hash representation of Model along with all loaded associations.

Returns:

  • (Hash<Symbol, Object>)

    the list of attribute names and associations, if loaded.



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