Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shopify Rails App: Triggering create callback for a shop re-install

I have a Shopify app that runs a callback when a new Shop is created. I just discovered a bug that when the app is uninstalled, then re-insalled, the callback isn't run because the shop isn't actually created again (I don't delete shops from my DB on uninstall).

class Shop < ActiveRecord::Base
  include ShopifyApp::Shop
  after_create :init_webhooks

   def self.store(session)
    shop = Shop.where(:shopify_domain => session.url).first_or_create({ shopify_domain: session.url, 
                                      :shopify_token => session.token,
                                      :installed => true})
    shop.id
  end

  def self.retrieve(id)
    shop = Shop.where(:id => id).first
    if shop
      ShopifyAPI::Session.new(shop.shopify_domain, shop.shopify_token)
    else
      nil
    end
  end

I could run a check to see if shop.installed = false, and then if it's false, I can init_webhooks. But I'm just not sure where I should be putting this logic. I don't know if it's appropriate to put inside the store or retrieve methods.

I'm wondering if there's something simple that I'm missing. Basically I want to run my init_webhooks if the webhooks don't exist.

EDIT: I tried the below solution of refactoring my callbacks into their own method whereby I could check to see if app is installed and then, if not, run the methods I want on new installs:

def self.retrieve(id)
    shop = Shop.where(:id = id).first
    if shop
      shop.boot
      ShopifyAPI::Session.new(shop.shopify_domain, shop.shopify_token)
    else
      nil
    end
  end

  def boot
    if !installed
      shopify_session
      init_webhooks
      self.installed = true
      self.save!
    end
  end

This seems to be working fine for brand new installs, but on a re-install, the user doesn't seem to authenticate (keeps redirecting to the /login page after entering shopify url)<

like image 404
Jackson Cunningham Avatar asked Nov 09 '22 04:11

Jackson Cunningham


1 Answers

You can put this check inside an Initializer so when the app is started, it only checks once and does any necessary setup before the rest of the app loads or begins to take requests.


References

http://guides.rubyonrails.org/configuring.html#using-initializer-files

like image 98
Anthony Michael Cook Avatar answered Nov 15 '22 04:11

Anthony Michael Cook