Class: Booqable::ResourceParser

Inherits:
Object
  • Object
show all
Defined in:
lib/booqable/resource_parser.rb

Overview

Parses JSON:API payloads into Sawyer::Resource objects

JSON:API formatted data (from webhooks or API responses) is converted into Ruby objects with dot-notation access for convenient attribute access.

Examples:

Parse a JSON:API payload

payload = '{"data":{"id":"123","type":"customers","attributes":{"name":"John"}}}'
customer = Booqable::ResourceParser.parse(payload)
customer.id   # => "123"
customer.name # => "John"

Parse with nested relationships

payload = {
  "data" => {
    "id" => "123",
    "type" => "orders",
    "attributes" => { "status" => "reserved" },
    "relationships" => {
      "customer" => { "data" => { "id" => "456", "type" => "customers" } }
    }
  },
  "included" => [
    { "id" => "456", "type" => "customers", "attributes" => { "name" => "John" } }
  ]
}
order = Booqable::ResourceParser.parse(payload)
order.customer.name # => "John"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(payload) ⇒ ResourceParser

Initialize a new ResourceParser

Parameters:

  • payload (String, Hash)

    JSON:API payload



45
46
47
# File 'lib/booqable/resource_parser.rb', line 45

def initialize(payload)
  @payload = payload
end

Class Method Details

.parse(payload) ⇒ Sawyer::Resource?

Parse a JSON:API payload into a Sawyer::Resource

Parameters:

  • payload (String, Hash)

    JSON:API payload (string or parsed hash)

Returns:

  • (Sawyer::Resource, nil)

    Parsed resource object with dot-notation access, or nil for empty/nil input



38
39
40
# File 'lib/booqable/resource_parser.rb', line 38

def self.parse(payload)
  new(payload).parse
end

Instance Method Details

#parseSawyer::Resource?

Parse the payload into a Sawyer::Resource

Returns:

  • (Sawyer::Resource, nil)

    Parsed resource or nil for empty input



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/booqable/resource_parser.rb', line 52

def parse
  return nil if @payload.nil?

  json_string = @payload.is_a?(String) ? @payload : @payload.to_json
  return nil if json_string.strip.empty?

  serializer = JsonApiSerializer.any_json
  decoded = serializer.decode(json_string)

  return nil unless decoded && decoded[:data]

  Sawyer::Resource.new(sawyer_agent, decoded[:data])
end