Module: TurboBoost::Commands::AttributeHydration

Extended by:
AttributeHydration
Included in:
AttributeHydration, AttributeSet, ControllerPack
Defined in:
lib/turbo_boost/commands/attribute_hydration.rb

Instance Method Summary collapse

Instance Method Details

#dehydrate(value) ⇒ Object

RULE: If an attribute value is a Hash

(not the `aria` or `data` key because those are handled by Rails)
and the Hash does not contain an object that implements GlobalID,
then the developer must convert the Hash to a JSON string manually.

SOLUTION: All data that’s not a scalar/primitive value should live in ‘data` or `aria`.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/turbo_boost/commands/attribute_hydration.rb', line 33

def dehydrate(value)
  return value unless has_sgid?(value)
  case value
  when Array
    value.map { |val| dehydrate val }
  when Hash
    value.each_with_object(HashWithIndifferentAccess.new) do |(key, val), memo|
      val = dehydrate(val)
      memo[key] = convert_to_json?(key, val) ? val.to_json : val
    end
  else
    implements_sgid?(value) ? value.to_sgid_param : value
  end
end

#hydrate(value) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/turbo_boost/commands/attribute_hydration.rb', line 6

def hydrate(value)
  case value
  when Array
    value.map { |val| hydrate(val) }
  when Hash
    value.each_with_object(HashWithIndifferentAccess.new) do |(key, val), memo|
      memo[key] = hydrate(val)
    end
  when String
    parsed_value = parse_json(value)
    hydrated_value = hydrate(parsed_value) unless parsed_value.nil?
    hydrated_value ||= GlobalID::Locator.locate_signed(value) if possible_sgid_string?(value)
    hydrated_value || value
  else
    value
  end
rescue => error
  Rails.logger.error "Failed to hydrate value! #{value}; #{error}"
  value
end