Class: SmartParams::Field

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

Constant Summary collapse

RECURSIVE_TREE =
->(accumulated, key) {accumulated[key] = Hash.new(&RECURSIVE_TREE)}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Field.



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

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.



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

def keychain
  @keychain
end

#subfieldsObject (readonly)

Returns the value of attribute subfields.



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

def subfields
  @subfields
end

#typeObject (readonly)

Returns the value of attribute type.



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

def type
  @type
end

#valueObject (readonly)

Returns the value of attribute value.



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

def value
  @value
end

Instance Method Details

#claim(raw) ⇒ Object



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

def claim(raw)
  if keychain.empty?
    @value = type[raw]
  else
    @value = type[raw.dig(*keychain)]
  end
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

Returns:

  • (Boolean)


24
25
26
# File 'lib/smart_params/field.rb', line 24

def deep?
  subfields.present?
end

#empty?Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/smart_params/field.rb', line 49

def empty?
  value.nil?
end

#field(key, type:, &subfield) ⇒ Object



20
21
22
# File 'lib/smart_params/field.rb', line 20

def field(key, type:, &subfield)
  @subfields << self.class.new(keychain: [*keychain, key], type: type, &subfield)
end

#to_hashObject



38
39
40
41
42
43
44
45
46
47
# File 'lib/smart_params/field.rb', line 38

def to_hash
  *chain, key = keychain
  Hash.new(&RECURSIVE_TREE).tap do |tree|
    if chain.any?
      tree.dig(*chain)[key] = value
    else
      tree[key] = value
    end
  end
end

#weightObject



53
54
55
# File 'lib/smart_params/field.rb', line 53

def weight
  keychain.length
end