Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## [Unreleased]

- **Breaking:** reading an attribute that is absent from an API payload now
raises `Booqable::MissingAttribute` (a `NoMethodError` subclass) instead of
silently returning nil.
- Support Ruby 4.0

## [1.2.1] - 2026-06-10
Expand Down
27 changes: 27 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,33 @@ customer = client.parse_resource(payload)

`deserialize_resource` is available as an alias for `parse_resource`.

## Strict attribute reads

Reading an attribute that is absent from the API payload raises
`Booqable::MissingAttribute` instead of silently returning nil, so typos and
renamed API fields fail loudly:

```ruby
customer.name # => "John Doe"
customer.full_name # raises Booqable::MissingAttribute (key absent from payload)
```

An attribute that is present in the payload with a null value still returns
nil — only absent keys raise:

```ruby
order.customer # => nil when the payload contains "customer": null
```

`Booqable::MissingAttribute` subclasses `NoMethodError`, so generic rescues
keep working. To probe for an attribute that may be absent, use hash-style
access or `key?`:

```ruby
order[:customer] # => nil when the key is absent (lenient probe)
order.key?(:customer) # => false when the key is absent
```

## Advanced usage

### Custom middleware
Expand Down
1 change: 1 addition & 0 deletions lib/booqable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
require_relative "booqable/version"
require_relative "booqable/rate_limit"
require_relative "booqable/error"
require_relative "booqable/strict_attributes"
require_relative "booqable/oauth_client"
require_relative "booqable/middleware/base"
require_relative "booqable/middleware/raise_error"
Expand Down
44 changes: 44 additions & 0 deletions lib/booqable/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,50 @@ class ServiceUnavailable < ServerError; end
# and body matches 'read-only'
class ReadOnlyMode < ServerError; end

# Raised when reading an attribute that is absent from an API resource
#
# Sawyer normally answers reads of absent attributes with nil, which turns
# typos and renamed API fields (e.g. `time_zone` vs `default_timezone`)
# into silent data bugs. Resources created by this gem raise this error
# instead — see {Booqable::StrictAttributes}.
#
# Attributes that are present in the payload with a null value still
# return nil; only reads of keys that are absent from the payload raise.
#
# This inherits from NoMethodError (not Booqable::Error) because an absent
# attribute is a programming error in the caller, not an API failure:
#
# * generic `rescue NoMethodError` / `rescue StandardError` code keeps working
# * ActiveSupport's `resource.try(:foo)` stays a safe probe: it returns nil
# without calling, since respond_to? is false for absent attributes
# (the bang variant `try!(:foo)` raises)
# * hash-style access stays a lenient, explicit probe: `resource[:foo]`
# returns nil for absent keys because Sawyer rescues NoMethodError there
class MissingAttribute < NoMethodError
# Initialize a new MissingAttribute error
#
# @param attribute_name [Symbol] Name of the absent attribute that was read
# @param resource [Sawyer::Resource] Resource the attribute was read from
def initialize(attribute_name, resource)
super(build_message(attribute_name, resource), attribute_name)
end

private

def build_message(attribute_name, resource)
message = +"undefined attribute `#{attribute_name}` for #{resource_description(resource)}. "
message << "The attribute is absent from the API payload "
message << "(attributes present with a null value return nil). "
message << "Available attributes: #{resource.attrs.keys.sort.join(", ")}"
message
end

def resource_description(resource)
type = resource.attrs[:type]
type.is_a?(String) ? "a Booqable #{type} resource" : "a Booqable resource"
end
end

# Raised when Booqable configuration is invalid
class ConfigArgumentError < ArgumentError; end

Expand Down
14 changes: 8 additions & 6 deletions lib/booqable/http.rb
Original file line number Diff line number Diff line change
Expand Up @@ -243,15 +243,17 @@ def faraday_builder

# Get or create the Sawyer agent for API requests
#
# Returns a memoized Sawyer::Agent configured with the API endpoint,
# serializer, and optional logging. Sawyer handles the low-level HTTP
# communication and response parsing.
# Returns a memoized Booqable::SawyerAgent configured with the API
# endpoint, serializer, and optional logging. Sawyer handles the
# low-level HTTP communication and response parsing. Resources created
# through this agent raise {Booqable::MissingAttribute} when an absent
# attribute is read (see {Booqable::StrictAttributes}).
#
# @return [Sawyer::Agent] HTTP agent instance
# @return [Booqable::SawyerAgent] HTTP agent instance
# @api private
def agent
@agent ||= Sawyer::Agent.new(api_endpoint,
sawyer_options) do |agent|
@agent ||= Booqable::SawyerAgent.new(api_endpoint,
sawyer_options) do |agent|
agent.response :logger, logger, bodies: true if logger
end
end
Expand Down
7 changes: 4 additions & 3 deletions lib/booqable/resource_parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -69,11 +69,12 @@ def parse
#
# The agent URL is a placeholder - we don't make any HTTP requests.
# We just need the agent to create Sawyer::Resource objects that
# provide dot-notation attribute access.
# provide dot-notation attribute access. Using Booqable::SawyerAgent
# makes attribute reads strict (see {Booqable::StrictAttributes}).
#
# @return [Sawyer::Agent]
# @return [Booqable::SawyerAgent]
def sawyer_agent
@sawyer_agent ||= Sawyer::Agent.new("https://example.com") do |http|
@sawyer_agent ||= Booqable::SawyerAgent.new("https://example.com") do |http|
http.headers[:content_type] = "application/json"
end
end
Expand Down
70 changes: 70 additions & 0 deletions lib/booqable/strict_attributes.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# frozen_string_literal: true

module Booqable
# Sawyer::Agent used for every resource this gem creates
#
# Behaves exactly like Sawyer::Agent. It exists as a marker so that
# {Booqable::StrictAttributes} can tell resources created by this gem
# apart from resources created by other Sawyer-based gems
# loaded in the same process.
class SawyerAgent < Sawyer::Agent
end

# Strict attribute reads for resources created by this gem
#
# Sawyer::Resource#method_missing silently answers reads of absent
# attributes with nil. That turns typos and renamed API fields
# (e.g. `time_zone` vs `default_timezone`) into silent data bugs.
# For resources created by a {Booqable::SawyerAgent}, this module raises
# {Booqable::MissingAttribute} instead — both for plain reads
# (`resource.foo`) and predicate reads (`resource.foo?`).
#
# Attributes that ARE present in the payload with a null value still
# return nil — only reads of keys that are absent from the payload raise.
#
# Everything else about Sawyer::Resource is unchanged: attribute writes
# (`resource.foo = 1`) still define new attributes, hash-style access
# (`resource[:foo]`) stays a lenient probe returning nil for absent keys,
# and `to_h`/`to_attrs`, `key?`, `dig`, `fetch`, enumeration, marshaling,
# and respond_to? semantics all behave as before. Resources created by
# other gems' Sawyer agents are unaffected.
module StrictAttributes
# Matches plain attribute reads (`foo`) and predicate reads (`foo?`).
# Setters (`foo=`) stay permitted since Sawyer allows adding attributes.
ATTRIBUTE_READ_PATTERN = /\A([a-z0-9_]+)(\?)?\z/i

# Raise {Booqable::MissingAttribute} for reads of absent attributes
# on strict resources; defer to Sawyer's behavior for everything else.
def method_missing(method, *)
attr_name = booqable_missing_attribute_read(method)
raise Booqable::MissingAttribute.new(attr_name, self) if attr_name

super
end

private

# Returns the attribute name when +method+ is a read of an attribute
# that is absent from the payload of a strict resource, nil otherwise
#
# @param method [Symbol] the method name passed to #method_missing
# @return [Symbol, nil]
def booqable_missing_attribute_read(method)
# _agent/_fields are Sawyer::Resource's public attr_readers — the bare `agent`/`fields`
# spellings are SPECIAL_METHODS resolved inside method_missing, so calling those from
# this hook (which method_missing invokes) would recurse infinitely.
return nil unless _agent.is_a?(Booqable::SawyerAgent)

match = ATTRIBUTE_READ_PATTERN.match(method.to_s)
return nil unless match

attr_name = match[1].to_sym
return nil if _fields.include?(attr_name)
return nil if match[2].nil? && Sawyer::Resource::SPECIAL_METHODS.include?(match[1])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Predicate checks on built-in resource accessors incorrectly raise an error instead of returning a value

The predicate form of Sawyer's built-in accessors (e.g. .agent?, .fields?, .rels?) is not exempted from the strict-read guard (booqable_missing_attribute_read at lib/booqable/strict_attributes.rb:63) because the special-methods bypass only fires for non-predicate calls, so these valid queries raise an error instead of returning a boolean.

Impact: Calling .agent?, .fields?, or .rels? on any API resource crashes with MissingAttribute instead of returning true.

Mechanism: the SPECIAL_METHODS guard is gated on match[2].nil?

At lib/booqable/strict_attributes.rb:63:

return nil if match[2].nil? && Sawyer::Resource::SPECIAL_METHODS.include?(match[1])

When the method is agent?, match[2] is "?" (not nil), so match[2].nil? is false and the entire guard is skipped. The code then falls through to return attr_name (:agent), which triggers MissingAttribute. Sawyer's own method_missing never gets a chance to handle the predicate form of the special method.

The fix is to drop the match[2].nil? && condition so both plain and predicate forms of special methods are passed through to Sawyer:

return nil if Sawyer::Resource::SPECIAL_METHODS.include?(match[1])
Suggested change
return nil if match[2].nil? && Sawyer::Resource::SPECIAL_METHODS.include?(match[1])
return nil if Sawyer::Resource::SPECIAL_METHODS.include?(match[1])
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.


attr_name
end
end
end

Sawyer::Resource.prepend(Booqable::StrictAttributes)
4 changes: 3 additions & 1 deletion spec/booqable/resource_proxy_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,9 @@
expect(orders).to be_an(Array)
expect(orders.length).to be > 0
order = orders.first
if order.customer
# Hash-style access is the lenient probe: this cassette's list payload
# has no customer key, and a strict read would raise MissingAttribute.
if order[:customer]
expect(order.customer).not_to be_an(Array)
expect(order.customer).to respond_to(:id)
expect(order.customer).to respond_to(:name)
Expand Down
Loading
Loading