Created
October 24, 2012 19:06
-
-
Save bsodmike/3948161 to your computer and use it in GitHub Desktop.
Decorator and Presenter Patterns in Rails 3.2.X
This file contains 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
require 'delegate' | |
class Decorator < BasicObject | |
undef_method :== | |
def initialize(component) | |
@component = component | |
end | |
def method_missing(name, *args, &block) | |
@component.send(name, *args, &block) | |
end | |
end |
This file contains 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 ListingDecorator < Decorator | |
# reader to access decorated object | |
def listing | |
@component | |
end | |
def at_state?(state) | |
listing.state == state.to_s | |
end | |
# Initialize a new decorator instance by passing in | |
# an instance of the source class. | |
# | |
# When passing in a single object, using `.decorate` is | |
# identical to calling `.new`. | |
def self.decorate(component) | |
new(component) | |
end | |
end |
This file contains 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 ListingPresenter | |
def initialize(component) | |
@component = component | |
end | |
def listing | |
@component | |
end | |
def progress_at(state) | |
# ... | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternative decorator based on
SimpleDelegator
Transparency in action
Ref: http://robots.thoughtbot.com/post/14825364877/evaluating-alternative-decorator-implementations-in