Module: Acfs::Resource::Attributes::ClassMethods

Defined in:
lib/acfs/resource/attributes.rb

Constant Summary collapse

ATTR_CLASS_BASE =
'::Acfs::Resource::Attributes'

Instance Method Summary collapse

Instance Method Details

#attribute(name, type, **opts) ⇒ Object

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::*`.

Examples:

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

Parameters:

  • name (#to_sym)

    Attribute name.

  • type (Symbol, String, Class)

    Attribute type identifier or type class.



203
204
205
206
207
208
209
# 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

#attributesHash{String => Object, Proc}

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

Examples:

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

Returns:

  • (Hash{String => Object, Proc})

    Attributes with default values.



226
227
228
229
230
# 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_attributesObject



232
233
234
235
236
237
238
# 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