Class: Showroom::ProductVariant

Inherits:
Resource
  • Object
show all
Defined in:
lib/showroom/models/product_variant.rb

Overview

Represents a Shopify product variant.

Examples:

variant = ProductVariant.new('title' => 'S / Red', 'price' => '899.00', 'available' => true)
variant.available? # => true
variant.on_sale?   # => false

Instance Attribute Summary

Attributes inherited from Resource

#attrs, #client

Instance Method Summary collapse

Methods inherited from Resource

#==, #[], has_many, has_one, #initialize, #inspect, main_attr_keys, main_attrs, #method_missing, #respond_to_missing?, #to_h

Constructor Details

This class inherits a constructor from Showroom::Resource

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Showroom::Resource

Instance Method Details

#availability_known?Boolean

Returns true when the source payload included an available key, making #available? authoritative.

Returns:

  • (Boolean)


29
30
31
# File 'lib/showroom/models/product_variant.rb', line 29

def availability_known?
  @attrs.key?('available')
end

#available?Boolean?

Returns true when the variant is available for purchase, false when explicitly unavailable, or nil when the source payload omits the available key (some Shopify storefronts do not expose it on /products/{handle}.json).

Returns:

  • (Boolean, nil)


19
20
21
22
23
# File 'lib/showroom/models/product_variant.rb', line 19

def available?
  return nil unless availability_known? # rubocop:disable Style/ReturnNilInPredicateMethodDefinition

  @attrs['available'] == true
end

#on_sale?Boolean

Returns true when compare_at_price is present and greater than price.

Returns:

  • (Boolean)


36
37
38
39
40
41
# File 'lib/showroom/models/product_variant.rb', line 36

def on_sale?
  cap = @attrs['compare_at_price']
  return false if cap.nil? || cap.to_s.empty?

  cap.to_f > @attrs['price'].to_f
end

#optionsArray<String>

Returns the selected options for this variant as an Array of values.

Collects option1, option2, option3 in order, omitting nil values.

Returns:

  • (Array<String>)


48
49
50
# File 'lib/showroom/models/product_variant.rb', line 48

def options
  [@attrs['option1'], @attrs['option2'], @attrs['option3']].compact
end