module Acfs::Resource::Attributes::ClassMethods

Constants

ATTR_CLASS_BASE

Public Instance Methods

attribute(name, type, **opts) click to toggle source

@api public

Define a model attribute by name and type. Will create getter and setter for given attribute name. Existing methods will be overridden.

Available types can be found in `Acfs::Model::Attributes::*`.

@example

class User < Acfs::Resource
  attribute :name, :string, default: 'Anon'
  attribute :email, :string, default: lambda{ "#{name}@example.org"}
end

@param [#to_sym] name Attribute name. @param [Symbol, String, Class] type Attribute

type identifier or type class.
# File lib/acfs/resource/attributes.rb, line 203
def attribute(name, type, **opts)
  if type.is_a?(Symbol) || type.is_a?(String)
    type = "#{ATTR_CLASS_BASE}::#{type.to_s.classify}".constantize
  end

  define_attribute(name.to_sym, type, **opts)
end
attributes() click to toggle source

@api public

Return list of possible attributes and default values for this model class.

@example

class User < Acfs::Resource
  attribute :name, :string
  attribute :age, :integer, default: 25
end
User.attributes # => { "name": nil, "age": 25 }

@return [Hash{String => Object, Proc}]

Attributes with default values.
# File lib/acfs/resource/attributes.rb, line 226
def attributes
  defined_attributes.each_with_object({}) do |(key, attr), hash|
    hash[key] = attr.default_value
  end
end
defined_attributes() click to toggle source
# File lib/acfs/resource/attributes.rb, line 232
def defined_attributes
  if superclass.respond_to?(:defined_attributes)
    superclass.defined_attributes.merge(local_attributes)
  else
    local_attributes
  end
end

Private Instance Methods

define_attribute(name, type, **opts) click to toggle source
# File lib/acfs/resource/attributes.rb, line 246
def define_attribute(name, type, **opts)
  name      = name.to_s
  attribute = type.new(**opts)

  local_attributes[name] = attribute
  define_attribute_method name

  send :define_method, name do
    read_attribute name
  end

  send :define_method, :"#{name}=" do |value|
    write_attribute name, value
  end
end
local_attributes() click to toggle source
# File lib/acfs/resource/attributes.rb, line 242
def local_attributes
  @local_attributes ||= {}
end