Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON-encode GlobalIDs as strings #149

Merged
merged 1 commit into from
Dec 16, 2022
Merged

JSON-encode GlobalIDs as strings #149

merged 1 commit into from
Dec 16, 2022

Conversation

georgeclaghorn
Copy link
Contributor

@georgeclaghorn georgeclaghorn commented Oct 31, 2022

Before:

> Plan.last.to_gid.as_json
{"uri"=>"gid://sandbox/Plan/186"}

> Plan.last.to_gid.to_json
"{\"uri\":\"gid://sandbox/Plan/186\"}"

After:

> Plan.last.to_gid.as_json
"gid://sandbox/Plan/186"

> Plan.last.to_gid.to_json
"\"gid://sandbox/Plan/186\""

This is particularly useful for JSON-serialized attributes in Rails, which use the result of #as_json on assigned values to generate the JSON they store.

class SubscriptionChange < ApplicationRecord
  serialize :old_product_gids, JSON
end

Before:

> SubscriptionChange.create!(old_product_gids: [ Plan.last.to_gid ]).old_product_gids
# => [{ "uri" => "gid://sandbox/Plan/186" }]

After:

> SubscriptionChange.create!(old_product_gids: [ Plan.last.to_gid ]).old_product_gids
# => [ "gid://sandbox/Plan/186" ]

@dhh dhh merged commit 40a2334 into rails:main Dec 16, 2022
@dhh
Copy link
Member

dhh commented Dec 16, 2022

Looks good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants