嗨我在Shopify應用程序中使用Shopify創業板,我正在尋找關於如何處理與Shopify API連接的建議。如何使用Shopify gem處理Shopify API連接?
我使用的webhooks和delayed_jobs,所以我需要一種方式來打開控制器之外的連接。
在我加入這個方法我店模式的時刻:
def connect_to_store
session = ShopifyAPI::Session.new(self.url, self.access_token)
session.valid?
ShopifyAPI::Base.activate_session(session)
end
這樣我就可以很輕鬆的打開連接,例如:
Shop.find(1).connect_to_store
ShopifyAPI::Shop.current.name
的問題是,我的產品裏面模塊,我需要在幾種方法中打開連接,但最終我多次調用connect_to_store方法,並且擔心打開多個連接到同一商店,而沒有真正的需要。
有沒有辦法檢查連接是否已經打開,只有在找不到另一個連接時纔打開連接?
感謝, 奧古斯托
------------------- -----------------更新 -
我更好地解釋我的問題。
假設在我的產品模型中,我想查看給定產品的compare_at_price是否大於其價格,並且在這種情況下,我想向Shopify產品添加「銷售」標籤。
在我的產品型號,我有:
class Product < ActiveRecord::Base
belongs_to :shop
def get_from_shopify
self.shop.connect_to_store
@shopify_p = ShopifyAPI::Product.find(self.shopify_id)
end
def add_tag(tag)
@shopify_p = self.get_from_shopify
shopify_p_tags = shopify_p.tags.split(",")
shopify_p_tags.collect{|x| x.strip!}
unless shopify_p_tags.include?(tag)
shopify_p_tags << tag
shopify_p_tags.join(",")
shopify_p.tags = shopify_p_tags
shopify_p.save
end
end
def on_sale?
@shopify_p = self.get_from_shopify
sale = false
shopify_p.variants.each do |v|
unless v.compare_at_price.nil?
if v.compare_at_price > v.price
sale = true
end
end
end
return sale
end
def update_sale_tag
if self.on_sale?
self.add_tag("sale")
end
end
end
我的問題是,如果我稱之爲:
p.update_sale_tag
的Shop.connect_to_store被稱爲幾次,我驗證了幾次,而我已經過身份驗證。
你會如何重構這段代碼?
這聽起來不錯!我不知道我應該在哪裏放置「開始...確保」代碼。 – Augusto 2012-07-12 05:58:37
我不知道我明白什麼是「ShopifyAPI :: Base」類?爲什麼你將.site屬性設置爲零後?我知道這是非常基本的,但我仍然不明白:( – Augusto 2012-07-12 16:19:37