Move option value naming logic into separate lib class

This commit is contained in:
Rob H
2014-06-04 14:54:42 +10:00
committed by Will Marshall
parent c21342b82e
commit e9f2a8f2cd
4 changed files with 200 additions and 182 deletions

View File

@@ -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