Module: Fortnox::Serialisation

Defined in:
lib/fortnox/serialisation.rb

Overview

JSON rendering for the three types a consumer can hold.

rest-easy generates JSON straight from the attribute hash, and JSON renders anything it doesn't recognise through to_s. Nested structs are the case that matters: without this, an invoice with rows serialises them as "#<Fortnox::Structs::InvoiceRow:0x…>".

All three render the model representation — snake_case attribute names — not the Fortnox wire format. Use to_api for the latter.

Defined Under Namespace

Modules: CollectionJSON, ResourceJSON, StructJSON

Class Method Summary collapse

Class Method Details

.filter(attributes, options) ⇒ Object

Applies Rails' :only / :except render options.

ActiveSupport's Hash#as_json slices a symbol-keyed hash, so a caller passing only: ['name'] would match nothing and silently render {}. Normalise both sides instead, and accept either spelling.

Anything that isn't an options hash is ignored — JSON.generate passes a JSON::State here when a resource is nested inside another structure.



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/fortnox/serialisation.rb', line 22

def self.filter(attributes, options)
  return attributes unless options.is_a?(::Hash)

  if options[:only]
    attributes.slice(*Array(options[:only]).map(&:to_sym))
  elsif options[:except]
    attributes.except(*Array(options[:except]).map(&:to_sym))
  else
    attributes
  end
end

.json_safe(value) ⇒ Object

Converts model values into JSON-safe primitives.



35
36
37
38
39
40
41
42
# File 'lib/fortnox/serialisation.rb', line 35

def self.json_safe(value)
  case value
  when Fortnox::Struct then json_safe(value.to_h)
  when ::Hash then value.to_h { |key, nested| [key.to_s, json_safe(nested)] }
  when ::Array then value.map { |element| json_safe(element) }
  else value
  end
end