Last active
July 8, 2016 14:56
-
-
Save hayesr/4bc046da7a2a2cec15af1cc568cec006 to your computer and use it in GitHub Desktop.
Simple Presenter System
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 ApplicationHelper | |
def present(object, klass = nil) | |
klass ||= "#{object.class}Presenter".constantize | |
presenter = klass.new(object, self) | |
yield presenter if block_given? | |
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 BasePresenter | |
def initialize(object, template) | |
@object = object | |
@template = template | |
end | |
private | |
def self.presents(name) | |
define_method(name) do | |
@object | |
end | |
end | |
def view | |
@template | |
end | |
def method_missing(*args, &block) | |
@template.send(*args, &block) | |
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 UserPresenter < BasePresenter | |
presents :user | |
delegate :username, to: :user | |
def avatar | |
site_link image_tag("avatars/#{avatar_name}", class: "avatar") | |
end | |
def linked_name | |
site_link(user.full_name.present? ? user.full_name : user.username) | |
end | |
def member_since | |
user.created_at.strftime("%B %e, %Y") | |
end | |
# ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment