Creating a custom shop repository

When an application is installed you may want to run a few tasks. To do this you nee to create a custom shop restory.

Start by creating a new model for your Shop repository.

bundle exec rails g model ShopSessionRepository
rm -f db/migrate/*_create_shop_session_repositories.rb spec/factories/shop_session_repositories.rb

Update app/models/shop_session_repository.rb so that it implements two methods, store and retrieve.

cat > app/models/shop_session_repository.rb << EOF
class ShopSessionRepository
  class << self
    def store(session)
      shop = Shop.find_or_initialize_by(shopify_domain: session.url)
      shop.shopify_token = session.token
      shop.save!
      shop.id
    end

    def retrieve(id)
      return unless id

      if shop = Shop.find_by(id: id)
        ShopifyAPI::Session.new(shop.shopify_domain, shop.shopify_token)
      end
    end
  end
end
EOF

Change config/initializers/shopify_session_repository.rb so that it uses your new repository instead of the Shop model.

if Rails.configuration.cache_classes
  ShopifyApp::SessionRepository.storage = ShopSessionRepository
else
  ActionDispatch::Reloader.to_prepare do
    ShopifyApp::SessionRepository.storage = ShopSessionRepository
  end
end

Remove from app/models/shop.rb

include ShopifyApp::SessionStorage

Restart the web server and test.

If everything is food them commit to version control.

git add app/models/shop.rb config/initializers/shopify_session_repository.rb app/models/shop_session_repository.rb spec/models/shop_session_repository_spec.rb
git commit -m "Use a custom shop session repository model"
git push

END OF PART 3!