嗨我在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