diff --git a/CHANGELOG.md b/CHANGELOG.md index ff01afa6..22640d39 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,7 +3,7 @@ Note: For changes to the API, see https://shopify.dev/changelog?filter=api ## Unreleased - +- Add `Session#copy_attributes_from` method ## 14.1.0 - [#1071](https://github.com/Shopify/shopify-api-ruby/issues/1071) Fix FulfillmentEvent class types diff --git a/lib/shopify_api/auth/session.rb b/lib/shopify_api/auth/session.rb index d4639fd0..1fba413b 100644 --- a/lib/shopify_api/auth/session.rb +++ b/lib/shopify_api/auth/session.rb @@ -121,6 +121,17 @@ def deserialize(str) end end + sig { params(other: Session).returns(Session) } + def copy_attributes_from(other) + JSON.parse(other.serialize).keys.each do |key| + next if key.include?("^") + + variable_name = "@#{key}" + instance_variable_set(variable_name, other.instance_variable_get(variable_name)) + end + self + end + sig { returns(String) } def serialize Oj.dump(self) diff --git a/test/auth/session_test.rb b/test/auth/session_test.rb index 59180854..4f55d392 100644 --- a/test/auth/session_test.rb +++ b/test/auth/session_test.rb @@ -143,9 +143,63 @@ def test_from_with_online_access_token_response assert_equal(expected_session, session) end + def test_copy_attributes_from + session_to = ShopifyAPI::Auth::Session.new( + id: "session-id", + shop: "shop", + state: "some-state", + access_token: "to-token", + scope: "read_products,read_themes", + associated_user_scope: "read_products", + expires: Time.now - 3600, + associated_user: build_user, + is_online: true, + shopify_session_id: "123", + ) + + session_from = ShopifyAPI::Auth::Session.new( + id: "session-id", + shop: "shop", + state: nil, + access_token: "from-token", + scope: "write_products,read_themes", + associated_user_scope: "write_products", + expires: Time.now + 24 * 3600, + associated_user: build_user, + is_online: true, + shopify_session_id: "456", + ) + + assert_equal(session_to, session_to.copy_attributes_from(session_from)) + + assert_equal(session_from.shop, session_to.shop) + assert_nil(session_to.state) + assert_equal(session_from.access_token, session_to.access_token) + assert_equal(session_from.scope, session_to.scope) + assert_equal(session_from.associated_user_scope, session_to.associated_user_scope) + assert_equal(session_from.expires, session_to.expires) + assert_equal(session_from.associated_user, session_to.associated_user) + assert_equal(session_from.shopify_session_id, session_to.shopify_session_id) + end + def teardown ShopifyAPI::Context.deactivate_session end + + private + + def build_user + ShopifyAPI::Auth::AssociatedUser.new( + id: 1, + first_name: "Hello #{Time.now}", + last_name: "World", + email: "Email", + email_verified: true, + account_owner: true, + locale: "en", + collaborator: false, + ) + end end end end