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.



13
14
15
16
17
18
19
20
21
# File 'lib/simple_params/attribute.rb', line 13

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.



9
10
11
# File 'lib/simple_params/attribute.rb', line 9

def default
  @default
end

#formatterObject (readonly)

Returns the value of attribute formatter.



11
12
13
# File 'lib/simple_params/attribute.rb', line 11

def formatter
  @formatter
end

#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

#typeObject (readonly)

Returns the value of attribute type.



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

def type
  @type
end

#validationsObject (readonly)

Returns the value of attribute validations.



10
11
12
# File 'lib/simple_params/attribute.rb', line 10

def validations
  @validations
end

Instance Method Details

#raw_valueObject



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

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

#valueObject



28
29
30
31
32
33
34
35
# File 'lib/simple_params/attribute.rb', line 28

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



37
38
39
40
41
42
43
44
# File 'lib/simple_params/attribute.rb', line 37

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