Class: Konfig::SchemaAttribute

Inherits:
Object
  • Object
show all
Defined in:
lib/konfig/schema_attribute.rb

Constant Summary collapse

TYPES =
[:string, :integer, :float, :boolean].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type: :string, array: nil, default: nil, description: nil, transformer: nil) ⇒ SchemaAttribute

Returns a new instance of SchemaAttribute.



16
17
18
19
20
21
22
23
24
# File 'lib/konfig/schema_attribute.rb', line 16

def initialize(name, type: :string, array: nil, default: nil, description: nil, transformer: nil)
  @name = name
  @array = array unless array.nil?
  self.type = type
  @default = default
  @description = description
  @transform_default = false
  @transformer = transformer
end

Instance Attribute Details

#arrayObject

Returns the value of attribute array.



13
14
15
# File 'lib/konfig/schema_attribute.rb', line 13

def array
  @array
end

#defaultObject



37
38
39
40
41
# File 'lib/konfig/schema_attribute.rb', line 37

def default
  return [] if @default.nil? && array?

  @default
end

#descriptionObject

Returns the value of attribute description.



12
13
14
# File 'lib/konfig/schema_attribute.rb', line 12

def description
  @description
end

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/konfig/schema_attribute.rb', line 8

def name
  @name
end

#transform_defaultObject

Returns the value of attribute transform_default.



11
12
13
# File 'lib/konfig/schema_attribute.rb', line 11

def transform_default
  @transform_default
end

#transformerObject

Returns the value of attribute transformer.



14
15
16
# File 'lib/konfig/schema_attribute.rb', line 14

def transformer
  @transformer
end

#typeObject

Returns the value of attribute type.



9
10
11
# File 'lib/konfig/schema_attribute.rb', line 9

def type
  @type
end

Instance Method Details

#array?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/konfig/schema_attribute.rb', line 43

def array?
  @array == true
end

#cast(value, handle_arrays: true) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/konfig/schema_attribute.rb', line 47

def cast(value, handle_arrays: true)
  return cast_array(value) if handle_arrays && array?

  return nil if value.nil?
  return nil if value.is_a?(String) && value.empty?

  send("cast_#{type}", value)
end

#transform(value) ⇒ Object



56
57
58
59
60
61
62
63
64
65
# File 'lib/konfig/schema_attribute.rb', line 56

def transform(value)
  casted = cast(value)
  return casted if transformer.nil?

  if array?
    casted.map { |v| transformer.call(v) }
  else
    transformer.call(casted)
  end
end