Skip to content

Instantly share code, notes, and snippets.

@dirkkelly
Created December 20, 2010 06:25
Show Gist options
  • Save dirkkelly/748085 to your computer and use it in GitHub Desktop.
Save dirkkelly/748085 to your computer and use it in GitHub Desktop.
A product page has a price, line items, orders and customers.
class ProductPage < Page
cattr_accessor :allowed_children
@@allowed_children = [Page,ArchivePage]
layout 'product'
field 'price'
part 'body'
part 'images'
after_create :set_price
def sku
url.gsub('\/','-')
end
def description
part('body').content if has_part('body')
end
def price
field('price').content.to_f unless field('price').nil?
end
def line_items
LineItem.all(:joins => :fields, :conditions => [ 'page_fields.name = ? AND page_fields.content = ?', 'product_id', self.id.to_s])
end
def customers
line_items.map(&:created_by).flatten.compact.uniq
end
def orders
line_items.map(&:parent).flatten.compact.uniq
end
def to_json(*attrs)
super self.class.params
end
def to_xml(*attrs)
super self.class.params
end
class << self
# Returns attributes attached to the product
def attrs
[ :id, :title, :created_at, :updated_at ]
end
# Returns methods with usefuly information
def methds
[ :price ]
end
# Returns a custom hash of attributes on the product
def params
{ :only => self.attrs, :methods => self.methds }
end
end
private
def set_price
self.price = (price || 0.00)
end
end
Product = ProductPage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment