Class: SmartParams::Field

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(keychain:, type:, &nesting) ⇒ Field



8
9
10
11
12
13
14
15
16
# File 'lib/smart_params/field.rb', line 8

def initialize(keychain:, type:, &nesting)
  @keychain = Array(keychain)
  @subfields = Set.new
  @type = type

  if block_given?
    instance_eval(&nesting)
  end
end

Instance Attribute Details

#keychainObject (readonly)

Returns the value of attribute keychain.



3
4
5
# File 'lib/smart_params/field.rb', line 3

def keychain
  @keychain
end

#subfieldsObject (readonly)

Returns the value of attribute subfields.



5
6
7
# File 'lib/smart_params/field.rb', line 5

def subfields
  @subfields
end

#typeObject (readonly)

Returns the value of attribute type.



6
7
8
# File 'lib/smart_params/field.rb', line 6

def type
  @type
end

#valueObject (readonly)

Returns the value of attribute value.



4
5
6
# File 'lib/smart_params/field.rb', line 4

def value
  @value
end

Instance Method Details

#claim(raw) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/smart_params/field.rb', line 22

def claim(raw)
  return type[dug(raw)] if deep?

  @value = type[dug(raw)]
rescue Dry::Types::ConstraintError => bad_type_exception
  raise SmartParams::Error::InvalidPropertyType, keychain: keychain, wanted: type, raw: if keychain.empty? then raw else raw.dig(*keychain) end
end

#deep?Boolean



18
19
20
# File 'lib/smart_params/field.rb', line 18

def deep?
  subfields.present?
end

#empty?Boolean



36
37
38
# File 'lib/smart_params/field.rb', line 36

def empty?
  value.nil?
end

#to_hashObject



30
31
32
33
34
# File 'lib/smart_params/field.rb', line 30

def to_hash
  keychain.reverse.reduce(value) do |accumulation, key|
    { key => accumulation }
  end
end

#weightObject



40
41
42
# File 'lib/smart_params/field.rb', line 40

def weight
  keychain.map(&:to_s)
end