Class: ActiveEntity::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/active_entity/attribute.rb

Overview

Examples:

Cast with given type option.

attr = ActiveEntity::Attribute.new(:user_id, type: Integer)
attr.cast!('12') #=> 12
attr.cast!('a') #=> raises ActiveEntity::CastError

Cast with given casting procedure.

attr = ActiveEntity::Attribute.new(
  :created_at,
  cast_by: -> (value) do
    case value
    when Fixnum, Float
      Time.at(value)
    when String
      Time.parse(value)
    else
      raise ActiveEntity::CastError.build(:Time, value)
    end
  end
)
attr.cast!(1420081200) #=> a Time object
attr.cast!('2015/01/01 12:00:00') #=> a Time object

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ Attribute

Returns a new instance of Attribute.

Parameters:

  • name (Symbol)
  • options (Hash{Symbol => Object}) (defaults to: {})

Raises:

  • (ArgumentError)


28
29
30
31
# File 'lib/active_entity/attribute.rb', line 28

def initialize(name, options = {})
  raise ArgumentError unless options.is_a?(Hash)
  @name, @options = name, options
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



24
25
26
# File 'lib/active_entity/attribute.rb', line 24

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



24
25
26
# File 'lib/active_entity/attribute.rb', line 24

def options
  @options
end

Instance Method Details

#cast!(value) ⇒ Object

Returns casted value.

Parameters:

  • value (Object)

Returns:

  • (Object)

    casted value

Raises:



46
47
48
49
50
51
52
53
54
55
# File 'lib/active_entity/attribute.rb', line 46

def cast!(value)
  case
  when type
    cast_by_defined_type(value)
  when cast_by
    cast_by.call(value)
  else
    value
  end
end

#cast_byProc

Returns:

  • (Proc)


39
40
41
# File 'lib/active_entity/attribute.rb', line 39

def cast_by
  @options[:cast_by]
end

#typeClass, ...

Returns:

  • (Class, Symbol, String)


34
35
36
# File 'lib/active_entity/attribute.rb', line 34

def type
  @options[:type]
end