Skip to content

Instantly share code, notes, and snippets.

@pithyless
Forked from jferris/application_controller.rb
Last active January 3, 2016 12:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pithyless/50457bdaadb21e88d282 to your computer and use it in GitHub Desktop.
Save pithyless/50457bdaadb21e88d282 to your computer and use it in GitHub Desktop.
Based on the original post (http://robots.thoughtbot.com/code-show-and-tell-polymorphic-finder), I think this would have been a simpler refactor.
class ApplicationController < ActionController::Base
private
def requested_purchaseable
RequestPurchase.new(params).find
end
end
RequestPurchase = Struct.new(:params) do
def find
product || individual_plan || team_plan || section || raise_unknown
end
private
def product
if id = params.slice(:product_id, :screencast_id, :book_id, :show_id).compact.first
Product.find(id)
end
end
def individual_plan
if id = params[:individual_plan_id]
IndividualPlan.where(sku: id).first!
end
end
def team_plan
if id = params[:team_plan_id]
TeamPlan.where(sku: id).first!
end
end
def section
if id = params[:section_id]
Section.find(id)
end
end
def raise_unknown
raise "Could not find a purchaseable object from given params: #{params}"
end
end
@stevebooks
Copy link

In what directory would you normally store request_purchase.rb?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment