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
13 changes: 13 additions & 0 deletions lib/resend/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,19 @@ def to_h

alias to_hash to_h

# Serialize response data without response headers
# @return [String] JSON representation of the response data
def to_json(*args)
@data.to_json(*args)
end

# Serialize response data for encoders that call as_json, such as ActiveSupport
# @param args [Array] Options forwarded to Hash#as_json when it is defined
# @return [Hash] The response data in as_json form
def as_json(*args)
@data.respond_to?(:as_json) ? @data.as_json(*args) : @data
end

# Get all keys from the data
# @return [Array] Array of keys
def keys
Expand Down
26 changes: 26 additions & 0 deletions spec/response_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,32 @@
end
end

describe "#to_json" do
it "serializes the data without response headers" do
expect(response.to_json).to eq(data.to_json)
end

it "works with JSON.generate" do
expect(JSON.generate(response)).to eq(JSON.generate(data))
end

it "works when nested in another object" do
expect(JSON.generate(response: response)).to eq(JSON.generate(response: data))
end

it "preserves JSON formatting options" do
expect(JSON.pretty_generate(response)).to eq(JSON.pretty_generate(data))
end

it "works when nested in a hash serialized with Hash#to_json" do
expect({ response: response }.to_json).to eq({ response: data }.to_json)
end

it "works when nested in an array serialized with Array#to_json" do
expect([response].to_json).to eq([data].to_json)
end
end

describe "enumeration" do
describe "#each" do
it "iterates over data" do
Expand Down
Loading