Created
April 19, 2012 02:08
-
-
Save mikepack/2417873 to your computer and use it in GitHub Desktop.
Exhibits and renderers
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 RailsTextPostRenderer | |
def initialize(context) | |
@context = context | |
end | |
def render(model) | |
@context.render(partial: "/posts/text_body", locals: {post: model}) | |
end | |
end | |
class TextPostExhibit < SimpleDelegator | |
def initialize(model, renderer) | |
@model, @renderer = model, renderer | |
super(model) | |
end | |
def render_body | |
@renderer.render(@model) | |
end | |
end | |
# Within the controller, and simplified without the ExhibitHelper | |
@post = TextPostExhibit.new(blog.post(params[:id]), RailsTextPostRenderer.new(self)) | |
# When rendering JSON | |
@post = TextPostExhibit.new(blog.post(params[:id]), JSONTextPostRenderer.new(self)) | |
# | |
# | |
# Which could then be refactored into... | |
# | |
# | |
class Exhibit < SimpleDelegator | |
def initialize(model, renderer) | |
@model, @renderer = model, renderer | |
super(model) | |
end | |
def render_body | |
@renderer.render(@model) | |
end | |
end | |
# Now we have only one exhibit which acts as a decorator and we've decoupled the rendering mechanism | |
@post = Exhibit.new(blog.post(params[:id]), RailsTextPostRenderer.new(self)) | |
# JSON uses the same exhibit but a different renderer | |
@post = Exhibit.new(blog.post(params[:id]), JSONTextPostRenderer.new(self)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment