Class: Comable::Variant

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
Ransackable, Quantifier
Defined in:
app/models/comable/variant.rb,
app/models/comable/variant/quantifier.rb

Defined Under Namespace

Modules: Quantifier

Instance Method Summary collapse

Methods included from Quantifier

#backorderable?, #can_supply?, #total_quantity, #track_inventory?

Instance Method Details

#as_json(options = {}) ⇒ Object



59
60
61
62
63
64
65
# File 'app/models/comable/variant.rb', line 59

def as_json(options = {})
  options = {
    include: { product: { except: :variants } },
    methods: [:text, :quantity, :option_names, :image_url]
  }
  super
end

#nameObject Also known as: text



45
46
47
48
49
50
51
# File 'app/models/comable/variant.rb', line 45

def name
  if options.any?
    "#{product.name} (#{options.map(&:value).join('/')})"
  else
    product.name
  end
end

#option_namesObject



55
56
57
# File 'app/models/comable/variant.rb', line 55

def option_names
  option_values.map(&:name)
end

#optionsObject



30
31
32
33
34
# File 'app/models/comable/variant.rb', line 30

def options
  option_values.map do |option_value|
    OpenStruct.new(type: option_value.option_type.try(:name), value: option_value.name)
  end
end

#options=(options) ⇒ Object



36
37
38
39
40
41
42
43
# File 'app/models/comable/variant.rb', line 36

def options=(options)
  options = JSON.parse(options) if options.is_a? String
  self.option_values = options.map do |option|
    hash = option.symbolize_keys
    option_type = Comable::OptionType.where(name: hash[:name]).first_or_initialize(&:save!)
    Comable::OptionValue.where(name: hash[:value], option_type: option_type).first_or_initialize(&:save!)
  end
end

#quantity=(quantity) ⇒ Object



25
26
27
28
# File 'app/models/comable/variant.rb', line 25

def quantity=(quantity)
  fail 'Stocks are already exists!' if stocks.any?
  stocks.build(quantity: quantity)
end