Skip to content

Instantly share code, notes, and snippets.

@elgalu
Last active December 19, 2015 17:09
Show Gist options
  • Save elgalu/5989410 to your computer and use it in GitHub Desktop.
Save elgalu/5989410 to your computer and use it in GitHub Desktop.
Decorator Pattern with Ruby in 8 lines - http://goo.gl/d960j
module Decorator
def initialize(decorated)
@decorated = decorated
end
def method_missing(method, *args)
args.empty? ? @decorated.send(method) : @decorated.send(method, args)
end
end
# app/decorators/article_decorator.rb
class ArticleDecorator < Draper::Decorator
delegate_all
def publication_status
if published?
"Published at #{published_at}"
else
"Unpublished"
end
end
def published_at
object.published_at.strftime("%A, %B %e")
end
def emphatic
h.content_tag(:strong, "Awesome")
end
end
# app/controllers/articles_controller.rb
def show
@article = Article.find(params[:id]).decorate
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment