Class: Philiprehberger::StructKit::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/struct_kit/field.rb

Constant Summary collapse

UNSET =
Object.new.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, type = nil, default: UNSET, coerce: nil) ⇒ Field

Returns a new instance of Field.



10
11
12
13
14
15
16
# File 'lib/philiprehberger/struct_kit/field.rb', line 10

def initialize(name, type = nil, default: UNSET, coerce: nil)
  @name = name
  @type = type
  @default = default
  @coerce = coerce
  @validations = []
end

Instance Attribute Details

#coerceObject (readonly)

Returns the value of attribute coerce.



8
9
10
# File 'lib/philiprehberger/struct_kit/field.rb', line 8

def coerce
  @coerce
end

#nameObject (readonly)

Returns the value of attribute name.



8
9
10
# File 'lib/philiprehberger/struct_kit/field.rb', line 8

def name
  @name
end

#typeObject (readonly)

Returns the value of attribute type.



8
9
10
# File 'lib/philiprehberger/struct_kit/field.rb', line 8

def type
  @type
end

#validationsObject (readonly)

Returns the value of attribute validations.



8
9
10
# File 'lib/philiprehberger/struct_kit/field.rb', line 8

def validations
  @validations
end

Instance Method Details

#add_validation(rule) ⇒ Object



43
44
45
# File 'lib/philiprehberger/struct_kit/field.rb', line 43

def add_validation(rule)
  @validations << rule
end

#coerce_value(value) ⇒ Object



18
19
20
21
22
23
# File 'lib/philiprehberger/struct_kit/field.rb', line 18

def coerce_value(value)
  return value if @coerce.nil?
  return @coerce.call(value) if @coerce.is_a?(Proc)

  value
end

#has_default?Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/philiprehberger/struct_kit/field.rb', line 25

def has_default?
  @default != UNSET
end

#resolve_defaultObject



29
30
31
# File 'lib/philiprehberger/struct_kit/field.rb', line 29

def resolve_default
  @default.respond_to?(:call) ? @default.call : @default
end

#type_valid?(value) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
41
# File 'lib/philiprehberger/struct_kit/field.rb', line 33

def type_valid?(value)
  return true if @type.nil?

  if @type.is_a?(Array)
    @type.any? { |t| value.is_a?(t) }
  else
    value.is_a?(@type)
  end
end

#validate_value(value) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/philiprehberger/struct_kit/field.rb', line 47

def validate_value(value)
  errors = []

  @validations.each do |rule|
    case rule
    when Hash
      errors << "#{@name} must be in range #{rule[:range]}" if rule[:range] && !rule[:range].include?(value)
      errors << "#{@name} does not match required format" if rule[:format] && !rule[:format].match?(value.to_s)
      errors << "#{@name} must be present" if rule[:presence] && blank?(value)
    when Proc
      msg = rule.call(value)
      errors << msg if msg.is_a?(String)
    end
  end

  errors
end