Module: FulfilApi::Resource::Serializable

Extended by:
ActiveSupport::Concern
Included in:
FulfilApi::Resource
Defined in:
lib/fulfil_api/resource/serializable.rb

Instance Method Summary collapse

Instance Method Details

#as_json(options = nil) ⇒ Hash

Overwrites the default #as_json method because ActiveModel will nest

the attributes when the model is transformed to JSON.

Parameters:

  • options (Hash, nil) (defaults to: nil)

    An optional list of options

Returns:

  • (Hash)

    A set of attributes available to be JSONified.



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/fulfil_api/resource/serializable.rb', line 31

def as_json(options = nil)
  # NOTE: We're including the model name by default. Otherwise, we can't use
  #   the {.from_json} method to parse it when reading from JSON.
  hash = to_h.merge("model_name" => @model_name)

  case options
  in { root: }
    { root => hash }
  else
    hash
  end
end

#to_json(options = nil) ⇒ String

Turns the FulfilApi::Resource into a JSON object.

Parameters:

  • options (Hash, nil) (defaults to: nil)

    An optional list of options

Returns:

  • (String)

    The JSONified resource data



48
49
50
# File 'lib/fulfil_api/resource/serializable.rb', line 48

def to_json(options = nil)
  as_json(options).to_json
end