如何提高Ruby结构的Shopify脚本性能

kq0g1dla  于 2022-11-04  发布在  Ruby
关注(0)|答案(1)|浏览(183)

我正在使用一个Ruby在Shopify脚本编辑器来管理作为一个安全措施的礼品与购买(GWP)促销。
当前脚本为:

  • 检查客户是以专业人员身份登录还是以未登录身份登录
  • 检查购物车中是否有最低消费金额
  • 确保购物车中仅添加了一件“礼品”产品
  • 如果结帐时没有“折扣码”或GWP_SETTINGS = []对象中设置的最小值,则删除“礼品”产品。

问题是它生成了太多的生产错误,如“您的脚本超出了时间限制”和“您的脚本超出了CPU限制”。
当前的使用量是CPU: 5% | Memory: 8%,并且每次我们添加一个新的GWP促销数组时,它都会令人眼花缭乱地增加。
是否有更好的方法来构建此逻辑,以便使用更少的内存来处理整个订单+ GWP验证?
以下是“行项目”结构:

cart = Input.cart

PRO_TAG = 'professional-tag'
has_pro_tag = cart.customer && cart.customer.tags.include?(PRO_TAG)

GWP_SETTINGS = [
    gwp_1 = { 
        "variant_id" => 98989898989898,
        "discount_code" => "DISCOUNT_CODE_1",
        "minimum_requirement" => Money.new(cents: 50 * 100),
        "user_type" => "consumer"
    },
    gwp_2 = { 
        "variant_id" => 97979797979797,
        "discount_code" => "DISCOUNT_CODE_1",
        "minimum_requirement" => Money.new(cents: 50 * 100),
        "user_type" => "consumer"
    },
    gwp_3 = { 
        "variant_id" => 96969696969696,
        "discount_code" => "DISCOUNT_CODE_1",
        "minimum_requirement" => Money.new(cents: 50 * 100),
        "user_type" => "consumer"
    }
]

def remove_GWP(cart, variant_id)
  cart.line_items.each do |item|
    next if item.variant.id != variant_id
    index = cart.line_items.find_index(item)
    cart.line_items.delete_at(index)
  end
end

def ensure_only_one_GWP_is_added(cart, variant_id)
  cart.line_items.each do |item|
    next if item.variant.id != variant_id
    item.instance_variable_set(:@quantity, 1)
  end
end

GWP_SETTINGS.each do |gwp_item_settings|

    customer_has_discount = cart.discount_code && cart.discount_code.code == gwp_item_settings["discount_code"]
    customer_has_minimum = cart.subtotal_price >= gwp_item_settings["minimum_requirement"]
    gwp_is_for_professional = gwp_item_settings["user_type"] == "professional-tag"

    #UNLOGGED
    if customer_has_discount && customer_has_minimum
        ensure_only_one_GWP_is_added(cart, gwp_item_settings["variant_id"])
    else
        remove_GWP(cart, gwp_item_settings["variant_id"])
    end

    #PRO
    if gwp_is_for_professional && has_pro_tag
      if customer_has_discount && customer_has_minimum
          ensure_only_one_GWP_is_added(cart, gwp_item_settings["variant_id"])
      else
          remove_GWP(cart, gwp_item_settings["variant_id"])
      end
    end

end

Output.cart = cart
fnx2tebb

fnx2tebb1#

你只有3个设置。但是一个客户(一个订单)可能有100多个行项目。你知道只有一个客户,一个订单,而你只有3个GWT设置可以使用。
如果你只对行项目进行一次循环,那么你的业务逻辑就会更聪明,你的算法就会是“这是我能走的最快的速度了,去城里”,你不能再快了。
对于诸如“此客户有X还是Y?"之类的问题,您只需执行一次,而不是每个行项目执行3次!
当你检查每一行项目时,你可以对可能影响该行项目的事情进行特殊的逻辑分析。
基本上,这是基本的算法。你在毫无理由地重复做尽可能多的工作,Shopify因此而呕吐。

相关问题