mirror of
https://github.com/openfoodfoundation/openfoodnetwork
synced 2026-03-21 05:09:15 +00:00
Move option value naming logic into separate lib class
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
require 'open_food_network/option_value_namer'
|
||||
|
||||
Spree::Variant.class_eval do
|
||||
has_many :exchange_variants, dependent: :destroy
|
||||
has_many :exchanges, through: :exchange_variants
|
||||
@@ -54,67 +56,11 @@ Spree::Variant.class_eval do
|
||||
delete_unit_option_values
|
||||
|
||||
option_type = self.product.variant_unit_option_type
|
||||
option_value_namer = OpenFoodNetwork::OptionValueNamer.new self
|
||||
if option_type
|
||||
name = option_value_name
|
||||
name = option_value_namer.name
|
||||
ov = Spree::OptionValue.where(option_type_id: option_type, name: name, presentation: name).first || Spree::OptionValue.create!({option_type: option_type, name: name, presentation: name}, without_protection: true)
|
||||
option_values << ov
|
||||
end
|
||||
end
|
||||
|
||||
def option_value_name
|
||||
value, unit = option_value_value_unit
|
||||
separator = value_scaled? ? '' : ' '
|
||||
|
||||
name_fields = []
|
||||
name_fields << "#{value}#{separator}#{unit}" if value.present? && unit.present?
|
||||
name_fields << unit_description if unit_description.present?
|
||||
name_fields.join ' '
|
||||
end
|
||||
|
||||
def value_scaled?
|
||||
self.product.variant_unit_scale.present?
|
||||
end
|
||||
|
||||
def option_value_value_unit
|
||||
if unit_value.present?
|
||||
if %w(weight volume).include? self.product.variant_unit
|
||||
value, unit_name = option_value_value_unit_scaled
|
||||
|
||||
else
|
||||
value = unit_value
|
||||
unit_name = self.product.variant_unit_name
|
||||
unit_name = unit_name.pluralize if value > 1
|
||||
end
|
||||
|
||||
value = value.to_i if value == value.to_i
|
||||
|
||||
else
|
||||
value = unit_name = nil
|
||||
end
|
||||
|
||||
[value, unit_name]
|
||||
end
|
||||
|
||||
def option_value_value_unit_scaled
|
||||
unit_scale, unit_name = scale_for_unit_value
|
||||
|
||||
value = unit_value / unit_scale
|
||||
|
||||
[value, unit_name]
|
||||
end
|
||||
|
||||
def scale_for_unit_value
|
||||
units = {'weight' => {1.0 => 'g', 1000.0 => 'kg', 1000000.0 => 'T'},
|
||||
'volume' => {0.001 => 'mL', 1.0 => 'L', 1000000.0 => 'ML'}}
|
||||
|
||||
# Find the largest available unit where unit_value comes to >= 1 when expressed in it.
|
||||
# If there is none available where this is true, use the smallest available unit.
|
||||
unit = units[self.product.variant_unit].select { |scale, unit_name|
|
||||
unit_value / scale >= 1
|
||||
}.to_a.last
|
||||
unit = units[self.product.variant_unit].first if unit.nil?
|
||||
|
||||
unit
|
||||
end
|
||||
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user