Skip to content

Instantly share code, notes, and snippets.

@scharfie
Created November 28, 2009 12:56
Show Gist options
  • Save scharfie/244500 to your computer and use it in GitHub Desktop.
Save scharfie/244500 to your computer and use it in GitHub Desktop.
# A very simplistic "presenter" implementation. It works by simply extending
# an object with a presenter module
# presenter.rb
module Presenter
def self.for_class(klass)
Object.const_get(klass.name + 'Presenter') rescue nil
end
# extends the given record with the presenter module for the object type
# (i.e. instance of Article will try to extend with ArticlePresenter)
def self.for(record)
(presenter = for_class(record.class)) ? record.extend(presenter) : record
end
end
# article.rb
class Article < ActiveRecord::Base
end
# article_presenter.rb
module ArticlePresenter
def published_at
published_at.eztime(':day :nmonth :year')
end
end
# usage
article = Presenter.for(Article.find(1))
article.published_at # => 28 November 2009
url_for(article) # => /articles/1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment