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:, root: false, &nesting) ⇒ Field

Returns a new instance of Field.



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

def initialize(keychain:, type:, root: false, &nesting)
  @root = root
  @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



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

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


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

def deep?
  subfields.present?
end

#empty?Boolean

Returns:

  • (Boolean)


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

def empty?
  value.nil?
end

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



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

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

#root?Boolean

Returns:

  • (Boolean)


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

def root?
  @root
end

#to_hashObject



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

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



56
57
58
# File 'lib/smart_params/field.rb', line 56

def weight
  keychain.length
end