Created
December 15, 2015 22:21
-
-
Save joeletizia/f0d4cfe39996b5553f10 to your computer and use it in GitHub Desktop.
Controller resources that are agnostic of content type to be rendered.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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