class Bart::Model

Attributes

identifier[RW]

The attribute of the model that can be used to uniquely identify an instance from any other. The primary attribute should also be set with `attribute <name>`.

Public Class Methods

attribute(name, type: nil, array: false) click to toggle source

Define a new attribute of the model. If `type` is given, a new instance of `type` will be created whenever this attribute is assigned a value. This allows creation of nested objects from a simple Hash. If `type` is given and `array` is true, the value given to this attribute will be interpreted as an array and a new instance of `type` will be created for each entry in the array It `type` is given, and the value given to this attribute is nil, no new instance of `type` will be created. Instead, the value will remain nil, as an instance of NilClass.

# File lib/bart_api/models.rb, line 18
def attribute name, type: nil, array: false
  attributes << [name, type]
  attr_reader name
  # Use a custom writer method to allow typed attributes to be
  # instantiated properly.
  define_method "#{name}=" do |value|
    # Only do type conversion if the type is specified and the value is
    # not nil.
    if type and !value.nil?
      # Lookup is done on Bart to ensure that Model subclasses are
      # searched first, falling back to other types (Numeric, Hash, etc.)
      # if no Model subclass is found.
      klass = Bart.const_get(type.to_s)
      value = array ? value.map{ |v| klass.new(v) } : klass.new(value)
    end
    instance_variable_set("@#{name}", value)
  end
end
attributes() click to toggle source

The list of attributes defined on the model

# File lib/bart_api/models.rb, line 38
def attributes
  @attributes ||= Set.new
end
delegate(*names, to: names.each do |name| def_delegator to, name) click to toggle source

Define one or more delegated methods on the model, passing them to the given attribute.

# File lib/bart_api/models.rb, line 52
def delegate *names, to:
  names.each do |name|
    def_delegator to, name
  end
primary_attribute(name) click to toggle source
# File lib/bart_api/models.rb, line 46
def primary_attribute name
  @identifier = name
end