class Upgrow::BasicModel

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.

Attributes

associations[R]

Public Class Methods

belongs_to(name) click to toggle source

Defines an association in the Model Schema.

@param name [Symbol] the name of the association.

# File lib/upgrow/basic_model.rb, line 17
def belongs_to(name)
  schema.association(name)
end
has_many(name) click to toggle source

Defines an association in the Model Schema.

@param name [Symbol] the name of the association.

# File lib/upgrow/basic_model.rb, line 24
def has_many(name)
  schema.association(name)
end
new(**args) click to toggle source

Initializes a new Model with the given member values.

@param args [Hash<Symbol, Object>] the list of values for each attribute

and association.

@raise [KeyError] if an attribute is missing in the list of arguments.

Calls superclass method
# 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

Public Instance Methods

to_h() click to toggle source

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

@return [Hash<Symbol, Object>] the list of attribute names

and associations, if loaded.
# 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

Private Instance Methods

method_missing(name, *args, &block) click to toggle source
Calls superclass method
# 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
respond_to_missing?(name, _include_private = false) click to toggle source
Calls superclass method
# File lib/upgrow/basic_model.rb, line 75
def respond_to_missing?(name, _include_private = false)
  associations.include?(name) || super
end