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
17
# 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]
  @validations = opts[:validations] || {}
end

Instance Attribute Details

#defaultObject (readonly)

Returns the value of attribute default.



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

def default
  @default
end

#formatterObject (readonly)

Returns the value of attribute formatter.



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

def formatter
  @formatter
end

#nameObject (readonly)

Returns the value of attribute name.



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

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

#typeObject (readonly)

Returns the value of attribute type.



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

def type
  @type
end

#validationsObject (readonly)

Returns the value of attribute validations.



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

def validations
  @validations
end

Instance Method Details

#raw_valueObject



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

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

#valueObject



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

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



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

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