Guest User

Untitled

a guest
Feb 21st, 2018
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. class Variant < ActiveRecord::Base
  2. belongs_to :product
  3. has_many :property_values, :dependent => :destroy, :after_add => :compare_stringified_prop_vals, :after_remove => :compare_stringified_prop_vals
  4.  
  5. acts_as_ferret :fields => { 'short_code' => { :boost => 2 }, 'property_values_string' => { :boost => 1 } }
  6.  
  7. def self.active_scope(allow_inactive = false, &block)
  8. raise ArgumentError, "block expected" if block.nil?
  9. return block.call if allow_inactive
  10. Variant.with_scope(:find => {:conditions => ['variants.active = ?', true]}, &block)
  11. end
  12.  
  13. def unit_price=(arg)
  14. upc = arg.to_f * 100
  15. raise ArgumentError, "strange unit price value #{arg.inspect}" unless (upc % 1) == 0
  16. self.unit_price_cents = upc
  17. end
  18.  
  19. def unit_price
  20. (self.unit_price_cents * 1.0) / 100
  21. end
  22.  
  23. def fq_path(parent = product())
  24. parent.fq_path + ';' + self.id.to_s
  25. end
  26.  
  27. # return the PropertyValue#text_value for a given Property or property_id
  28. def property_text_value(prop)
  29. (property_value_for(prop) or return nil).text_value
  30. end
  31.  
  32. # return the PropertyValue object for a given Property or property_id
  33. # bah - this could be more efficient
  34. def property_value_for(prop)
  35. prop = prop.id if prop.is_a? Property
  36. property_values.detect {|x| x.property_id == prop }
  37. end
  38.  
  39. # creates or updates property_values given a hash of property_id => text_value pairs
  40. def property_text_values=(ptv_hash)
  41. ptv_hash.each do |key, value|
  42. if propval = property_value_for(key.to_i)
  43. propval.update_attributes(:text_value => value)
  44. else
  45. property_values.build(:property_id => key, :text_value => value)
  46. end
  47. end
  48. end
  49.  
  50. def stringify_property_values
  51. text_values = []
  52. self.property_values.each do |pv|
  53. text_values << pv.text_value unless pv.text_value.strip.blank?
  54. end
  55. self.property_values_string = text_values.join(", ").squeeze(" ")
  56. end
  57.  
  58. def compare_stringified_prop_vals
  59. old_val = String.new(self.stringify_property_values)
  60. self.stringify_property_values
  61. self.save unless old_val == self.stringify_property_values
  62. end
  63.  
  64. end
Add Comment
Please, Sign In to add comment