Skip to content

Instantly share code, notes, and snippets.

@pete-a
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pete-a/d4b26b29c487319d2247 to your computer and use it in GitHub Desktop.
Save pete-a/d4b26b29c487319d2247 to your computer and use it in GitHub Desktop.
Switch vs Duck Typing
order_type = params[:order_type]
if(order_type == 'chronological')
products.order_by_date
elsif(order_type == 'alphabetical')
products.order_by_name
elsif(order_type == 'price')
products.order_by_price
else
# ... order alist by some default
products
end
order_type = params[:order_type]
case order_type
when 'choronological'
products.order_by_date
when 'alphabetical'
products.order_by_name
when 'price'
products.order_by_price
else
products
end
order_type = params[:order_type]
ordered_products = Product.order(products, order_type)
class Product
PRODUCT_ORDERERS = [NameOrderer.new, PriceOrderer.new, CategoryOrder.new, DateOrderer.new]
# ...
def self.order(products, order_type)
PRODUCT_ORDERERS.each do |orderer|
return orderer.order(products) if orderer.match?(order_type)
end
# Return the products in the orginal order if no orderer is found
products
end
end
class PriceOrderer
def match?(order_string)
order_string == 'price'
end
def order(products)
price_ordered_products = # ... logic to order collection
price_ordered_products
end
end
class Product
def self.order(products, order_type)
product_orderers.each do |orderer|
return orderer.order(products) if orderer.match?(order_type)
end
# Return the products in the orginal order if no orderer is found
products
end
private
def product_orderers
Dir["/path/to/product_orderers/*.rb"].map do |file|
require file
file_name = File.basename(file.path, '.rb')
# using ActiveSupport for camelcase and constantize
file_name.camelcase.constantize.new
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment