Skip to content

Instantly share code, notes, and snippets.

@alexkojin
Last active October 13, 2016 08:39
Show Gist options
  • Save alexkojin/76eee737a4aa4de7b66de8f8a73fecd4 to your computer and use it in GitHub Desktop.
Save alexkojin/76eee737a4aa4de7b66de8f8a73fecd4 to your computer and use it in GitHub Desktop.
Use class in rails helper
module ProductPriceHelper
# Render detailed product's price
def product_price(product)
ProductPrice.new(self, product).render
end
# render price for listing of products
def listing_price(product)
ProductPrice.new(self, product).render_for_listing
end
class ProductPrice < Struct.new(:view, :product)
delegate :content_tag, :number_to_currency, to: :view
def render
price = if product.has_variations?
price_range = if product.lowest_price && product.highest_price && product.lowest_price != product.highest_price
"#{format_price(product.lowest_price)} - #{format_price(product.highest_price)}"
elsif product.lowest_price
format_price(product.lowest_price)
else
format_price(product.price)
end
price_tag('price', 'Price', price_range)
elsif product.sale_price
if product.price > product.sale_price
price_tag('price', 'Price', format_price(product.price), 'cross-out') +
price_tag('sale-price', 'Sale', format_price(product.sale_price)) +
save_price_tag
else
price_tag('price', 'Price', format_price(product.price))
end
elsif product.list_price && product.amount_saved
price_tag('list-price', 'List Price', format_price(product.list_price), 'cross-out') +
price_tag('price', 'Price', format_price(product.price)) +
save_price_tag
else
price_tag('price', 'Price', format_price(product.price))
end
content_tag(:div, price, id: 'product-prices')
end
def render_for_listing
price = if product.lowest_price && product.highest_price && product.lowest_price != product.highest_price
"#{format_price(product.lowest_price)} - #{format_price(product.highest_price)}"
elsif product.lowest_price
format_price(product.lowest_price)
elsif product.sale_price
if product.price > product.sale_price
content_tag(:span, format_price(product.sale_price), class: 'sale-price') +
content_tag(:span, format_price(product.price), class: 'cross-out')
else
format_price(product.price)
end
else
format_price(product.price)
end
content_tag(:div, price, class: 'price')
end
private
def price_tag(id, label, value, css_class='')
content_tag(:div, id: id, class: "price #{css_class}") do
content_tag(:div, label, class: 'label') + content_tag(:div, value, class: 'value')
end
end
def save_price_tag
content_tag(:div, id: 'amount-saved', class: 'price') do
content_tag(:div, 'Saved', class: 'label') +
content_tag(:div, format_price(product.amount_saved), class: 'value') +
content_tag(:span, "(%#{product.percentage_saved})", id: 'percentage-saved')
end
end
def format_price(amount)
number_to_currency(amount / 100.0) if amount
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment