Module: StronglyTyped::Attributes

Defined in:
lib/strongly_typed/attributes.rb

Instance Method Summary collapse

Instance Method Details

#attribute(name, type = Object) ⇒ Object

Create attribute accesors for the included class

Also validations and coercions for the type specified

Examples:

class Person
  include StronglyTyped::Model

  attribute :id, Integer
  attribute :slug, String
end

Person.new(id: 1, slug: 'elgalu')
#=> #<Person:0x00c98 @id=1, @slug="elgalu">
leo.id   #=> 1
leo.slug #=> "elgalu"

Parameters:

  • name (Symbol)

    the accessor name

  • type (Class) (defaults to: Object)

    the class type to use for validations and coercions

Raises:

  • (NameError)


22
23
24
25
26
27
28
29
30
# File 'lib/strongly_typed/attributes.rb', line 22

def attribute(name, type=Object)
  name = name.to_sym #normalize

  raise NameError, "attribute `#{name}` already created" if members.include?(name)
  raise TypeError, "second argument, type, must be a Class but got `#{type.inspect}` insted" unless type.is_a?(Class)
  raise TypeError, "directly converting to Bignum is not supported, use Integer instead" if type == Bignum

  new_attribute(name, type)
end

#attributesHash

Memoized hash storing keys for names & values for types pairs

Returns:

  • (Hash)

    attributes



35
36
37
# File 'lib/strongly_typed/attributes.rb', line 35

def attributes
  @attributes ||= {}
end

#membersArray<Symbol>

Returns the attribute names created with attribute()

Returns:

  • (Array<Symbol>)

    all the attribute names



42
43
44
# File 'lib/strongly_typed/attributes.rb', line 42

def members
  attributes.keys
end