Module: Barion::JsonSerializer

Extended by:
ActiveSupport::Concern
Included in:
Address, GiftCardPurchase, Item, PayerAccount, Payment, PaymentTransaction, Purchase
Defined in:
app/models/concerns/barion/json_serializer.rb

Overview

JSON serialization solution for Barion

Instance Method Summary collapse

Instance Method Details

#deserialize(hash, options = {}) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'app/models/concerns/barion/json_serializer.rb', line 31

def deserialize(hash, options = {})
  options ||= deserialize_options
  deserialize_options.merge(options)
  return unless deserialize_options.key?(:map)

  map = deserialize_options[:map]
  convert_values(hash, map[:values], &map[:values][:_all]) if map.key?(:values)
  return unless map.key?(:keys)

  convert_keys(hash, map[:keys], &map[:keys][:_all])
end

#deserialize_optionsObject



12
13
14
# File 'app/models/concerns/barion/json_serializer.rb', line 12

def deserialize_options
  {}
end

#key_namesObject



16
17
18
# File 'app/models/concerns/barion/json_serializer.rb', line 16

def key_names
  {}
end

#process_response(response) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'app/models/concerns/barion/json_serializer.rb', line 43

def process_response(response)
  exceptions = deserialize_options.fetch(:except, {})
  associations = deserialize_options.fetch(:assoc, {})

  hash = deserialize(response)
  hash.map do |key, value|
    next if exceptions.include?(key.to_sym)

    association = self.class.reflect_on_association(key)
    if association
      (model_key_name, key_name) = associations[key.to_sym].shift
      value.each do |params|
        id = params[key_name]
        item = association.klass.send("find_by_#{model_key_name}", id)
        item.send(:process_response, params.compact!)
      end
    elsif respond_to?("#{key}=")
      send("#{key}=", value)
    end
  end
end

#serializable_hash(options = {}) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'app/models/concerns/barion/json_serializer.rb', line 20

def serializable_hash(options = {})
  options ||= serialize_options
  result = super(serialize_options.merge(options))
  if serialize_options.key?(:map)
    map = serialize_options[:map]
    convert_values(result, map[:values], &map[:values][:_all]) if map.key?(:values)
    convert_keys(result, map[:keys], &map[:keys][:_all]) if map.key?(:keys)
  end
  result.compact!
end

#serialize_optionsObject



8
9
10
# File 'app/models/concerns/barion/json_serializer.rb', line 8

def serialize_options
  {}
end