Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Variant < ActiveRecord::Base
- belongs_to :product
- has_many :property_values, :dependent => :destroy, :after_add => :compare_stringified_prop_vals, :after_remove => :compare_stringified_prop_vals
- acts_as_ferret :fields => { 'short_code' => { :boost => 2 }, 'property_values_string' => { :boost => 1 } }
- def self.active_scope(allow_inactive = false, &block)
- raise ArgumentError, "block expected" if block.nil?
- return block.call if allow_inactive
- Variant.with_scope(:find => {:conditions => ['variants.active = ?', true]}, &block)
- end
- def unit_price=(arg)
- upc = arg.to_f * 100
- raise ArgumentError, "strange unit price value #{arg.inspect}" unless (upc % 1) == 0
- self.unit_price_cents = upc
- end
- def unit_price
- (self.unit_price_cents * 1.0) / 100
- end
- def fq_path(parent = product())
- parent.fq_path + ';' + self.id.to_s
- end
- # return the PropertyValue#text_value for a given Property or property_id
- def property_text_value(prop)
- (property_value_for(prop) or return nil).text_value
- end
- # return the PropertyValue object for a given Property or property_id
- # bah - this could be more efficient
- def property_value_for(prop)
- prop = prop.id if prop.is_a? Property
- property_values.detect {|x| x.property_id == prop }
- end
- # creates or updates property_values given a hash of property_id => text_value pairs
- def property_text_values=(ptv_hash)
- ptv_hash.each do |key, value|
- if propval = property_value_for(key.to_i)
- propval.update_attributes(:text_value => value)
- else
- property_values.build(:property_id => key, :text_value => value)
- end
- end
- end
- def stringify_property_values
- text_values = []
- self.property_values.each do |pv|
- text_values << pv.text_value unless pv.text_value.strip.blank?
- end
- self.property_values_string = text_values.join(", ").squeeze(" ")
- end
- def compare_stringified_prop_vals
- old_val = String.new(self.stringify_property_values)
- self.stringify_property_values
- self.save unless old_val == self.stringify_property_values
- end
- end
Add Comment
Please, Sign In to add comment