Saltar al contenido
Ejemplos de Scripts

Migrating a Shopify Script Creator script

Merchants who could not write Ruby used a generator, so the most common paste in the world is not hand-written at all. The 200 lines of class definitions are boilerplate; the array at the bottom is the offer.

Reconstruido
Qué hacía el Script

It ran each campaign in the CAMPAIGNS array against the cart, in order, using a fixed library of qualifier and discount classes.

Pruébalo en tu propia tienda

Pégalo en Rescate de scripts y mira qué reconstruye

  1. Copia el Ruby con el botón que hay junto a cualquier Script de esta página.
  2. En tu panel de Shopify, abre Stackable, luego Herramientas y luego Rescate de scripts.
  3. Pégalo ahí, lee lo que la herramienta dice que va a crear y compáralo con los ajustes de esta página.

Rescate de scripts está en el plan Pro. No se publica nada hasta que le digas cuánto descontaba tu Script antiguo y las dos cifras coincidan al céntimo.

El Script

Reconstruido
El Ruby original

# GENERATED BY THE SHOPIFY SCRIPT CREATOR APP
# Version 0.12.0

class Campaign
  def initialize(condition, *qualifiers)
    @condition = (condition.to_s + '?').to_sym
    @qualifiers = PostCartAmountQualifier ? [] : [] rescue qualifiers.compact
    @line_item_selector = qualifiers.last unless @line_item_selector
    qualifiers.compact.each do |qualifier|
      is_multi_select = qualifier.instance_variable_get(:@conditions).is_a?(Array)
      if is_multi_select
        qualifier.instance_variable_get(:@conditions).each do |nested_q|
          @post_amount_qualifier = nested_q if nested_q.is_a?(PostCartAmountQualifier)
          @qualifiers << qualifier
        end
      else
        @post_amount_qualifier = qualifier if qualifier.is_a?(PostCartAmountQualifier)
        @qualifiers << qualifier
      end
    end if @qualifiers.empty?
  end

  def qualifies?(cart)
    return true if @qualifiers.empty?
    @qualifiers.send(@condition) do |qualifier|
      is_selector = false
      if qualifier.is_a?(Selector) || qualifier.is_a?(Array)
        is_selector = true
      end rescue nil
      if is_selector
        raise 'Missing line item match type' if @li_match_type.nil?
        cart.line_items.send(@li_match_type) { |item| qualifier.match?(item) }
      else
        qualifier.match?(cart, @selector)
      end
    end
  end
end

class ProductTagSelector < Selector
  def initialize(match_type, match_condition, tags)
    @match_condition = match_condition
    @invert = match_type == :does_not
    @tags = tags.map(&:downcase)
  end

  def match?(line_item)
    product_tags = line_item.variant.product.tags.to_a.map(&:downcase)
    case @match_condition
      when :match
        return @invert ^ ((@tags & product_tags).length > 0)
      else
        return @invert ^ partial_match(@match_condition, product_tags, @tags)
    end
  end
end

class PercentageDiscount
  def initialize(percent, message)
    @percent = Decimal.new(percent) / 100.0
    @message = message
  end

  def apply(line_item)
    line_discount = line_item.line_price * @percent
    new_line_price = line_item.line_price - line_discount
    line_item.change_line_price(new_line_price, message: @message)
  end
end

CAMPAIGNS = [
  ConditionalDiscount.new(
    :all,
    nil,
    nil,
    ProductTagSelector.new(:does, :match, ["sale"]),
    PercentageDiscount.new(20, "20% off sale items"),
    0
  ),
].freeze

CAMPAIGNS.each do |campaign|
  campaign.run(Input.cart)
end

Output.cart = Input.cart
En qué se convierte

Reconocido como Percentage off y reconstruido como una oferta de tipo volume. Estas son las claves de configuración reales con las que se guarda la oferta, así que puedes comparar tu propia reconstrucción campo por campo.

Cada ajuste, detallado
AjusteValorClave de configuración
Offer typevolumetype
Countingper_productcounting
Recurrenceoncerecurrence
Tier 1min qty 1 -> 20% offtiers[0]
Target scopetagstarget.scope
Target includessaletarget.includeIds
MethodautomaticdiscountMethod
Allocationstandardstacking.allocation
Combines with other discountsnostacking
Se te pedirá que confirmes
  • Your Script limited this to a tag, vendor, or product type. We carried that filter over, so confirm it selects the products you expect.
El carrito que lo demuestra

Creado en nuestra tienda de demostración pública, Meridian Goods, para que cada precio de aquí se pueda reproducir en lugar de darlo por bueno. El descuento de abajo es lo que calcula para este carrito exacto el mismo motor que se ejecuta en el pago.

El carrito que activa esta oferta, y lo que cuesta
ArtículoCant.Precio unit.
Ceramic Travel Mug1$22.00
Subtotal$22.00
Descuento-$4.40
Total$17.60

Sin sesión iniciada, o con sesión de un cliente sin etiquetas.

La cifra con la que la herramienta te compara

Antes de publicar, la herramienta pregunta qué hacía tu Script antiguo con un carrito que ya tienes. Ponlo en 1 de Ceramic Travel Mug a $22.00 y la respuesta queda fijada.

El descuento es $4.40. El total que pagó el comprador es $17.60.

La comparación es exacta, hasta la unidad más pequeña de tu moneda. Un céntimo de diferencia y la publicación sigue bloqueada, que es todo el sentido de este paso.

El carrito que no debe producir nada
  • swap the cart for a single Braided USB-C Cable
El carrito que no debe activar esta oferta
ArtículoCant.Precio unit.
Braided USB-C Cable1$14.00
Subtotal$14.00
Total$14.00

Sin sesión iniciada, o con sesión de un cliente sin etiquetas.

Preguntas frecuentes

Will Stackable rebuild this script?
Yes. Every spelling on this page is rebuilt today as a volume offer, and the cart above is the one that proves it.
What cart proves it works?
1 x Ceramic Travel Mug at $22.00. The engine takes $4.40 off, and checkout charges $17.60.
What will I have to check before publishing?
Your Script limited this to a tag, vendor, or product type. We carried that filter over, so confirm it selects the products you expect.

Formas de Script relacionadas

Help Center script template

The dialect Shopify’s own documentation taught, with its settings block above a do-not-edit banner.

Pega tu Script y mira cómo se reconstruye

La reconstrucción se compara con el dinero que cobraba tu Script antiguo antes de que puedas publicarla.

Usamos cookies esenciales para el funcionamiento de este sitio y, solo con tu permiso, cookies analíticas para entender el tráfico. Lee nuestra Política de cookies.