Skip to content

Instantly share code, notes, and snippets.

@joeletizia
Created December 15, 2015 22:21
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 joeletizia/b504f2bd76032a8bfd28 to your computer and use it in GitHub Desktop.
Save joeletizia/b504f2bd76032a8bfd28 to your computer and use it in GitHub Desktop.
Controller resources that are agnostic of content type to be rendered.
module Products
# What if we want to differ the content between iOS and Web?
class IndexResource
def initialize(product_presenters, content_type)
@product_presenters = product_presenters
@content_type = content_type
end
def render(rendering_engine = RenderingEngine)
rendering_engine.render(partial_path, product_presenters: product_presenters)
end
private
def partial_path
"/path/to/templates/index.#{content_type}.erb"
end
attr_reader :content_type, :product_presenters
end
class ShowResource
def initialize(product_presenter, content_type)
@product_presenter = product_presenter
@content_type = content_type
end
def render(rendering_engine = RenderingEngine)
rendering_engine.render(partial_path, product_presenter: product_presenter)
end
private
def partial_path
"/path/to/templates/show.#{content_type}.erb"
end
attr_reader :content_type, :product_presenter
end
end
class ProductsController < ApplicationController
def index
products = Product.all
product_presenters = ProductPresenter.wrap_many(products)
Products::IndexResource.new(product_presenters, content_type).render
end
def show
product = Product.find(params[:id])
product_presenter = ProductPresenter.new(product)
Products::ShowResource.new(product_presenter, content_type).render
end
private
def content_type
# switch on the requested format
if json?
:json
elsif web?
:html
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment