Class: SimpleParams::Attribute

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent, name, opts = {}) ⇒ Attribute

Returns a new instance of Attribute.



9
10
11
12
13
14
15
16
# File 'lib/simple_params/attribute.rb', line 9

def initialize(parent, name, opts={})
  @parent = parent
  @name = name.to_sym
  @type = TYPE_MAPPINGS[opts[:type]]
  @value = nil
  @default = opts[:default]
  @formatter = opts[:formatter]
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



7
8
9
# File 'lib/simple_params/attribute.rb', line 7

def name
  @name
end

#parentObject (readonly)

Returns the value of attribute parent.



6
7
8
# File 'lib/simple_params/attribute.rb', line 6

def parent
  @parent
end

Instance Method Details

#raw_valueObject



18
19
20
21
# File 'lib/simple_params/attribute.rb', line 18

def raw_value
  empty = @value.nil? || (@value.is_a?(String) && @value.blank?)
  empty ? default : @value
end

#valueObject



23
24
25
26
27
28
29
30
# File 'lib/simple_params/attribute.rb', line 23

def value
  return raw_value if raw_value.blank?
  if @formatter.present?
    Formatter.new(@parent, @formatter).format(raw_value)
  else
    raw_value
  end
end

#value=(val) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/simple_params/attribute.rb', line 32

def value=(val)
  @value = if @type.present?
    virtus_attr = Virtus::Attribute.build(@type)
    virtus_attr.coerce(val)
  else
    val
  end
end