Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@koppen
Last active November 7, 2016 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koppen/81776a8c45cb84f2b0b48c582250fbe9 to your computer and use it in GitHub Desktop.
Save koppen/81776a8c45cb84f2b0b48c582250fbe9 to your computer and use it in GitHub Desktop.
# frozen_string_literal: true
# A generic presenter class
class Presenter < SimpleDelegator
attr_reader :view
class << self
# Returns true if object has been wrapped in a Presenter
def decorated?(object)
object.is_a?(Presenter)
end
# Wrap object in presenter with access to a view context
def present(object, view)
return object if decorated?(object)
new(object, view)
end
# Wrap each object in presenter with access to a view context
def present_collection(collection, view)
collection.map do |item|
present(item, view)
end
end
end
def initialize(object, view)
super(object)
@view = view
end
def object
undecorated(__getobj__)
end
private
def decorated?(object)
self.class.decorated?(object)
end
def present_collection(collection, presenter)
presenter.present_collection(collection, view)
end
def undecorated(potentially_decorated_object)
if decorated?(potentially_decorated_object)
potentially_decorated_object.object
else
potentially_decorated_object
end
end
end
# frozen_string_literal: true
module PresentersHelper
# Returns object wrapped in presenter. If object is a collection each member
# of the collection is wrapped and the collection is returned.
#
# Example
#
# <%- @foo = present(@foo, FooPresenter) -%>
#
def present(object, presenter)
if object.is_a?(Enumerable)
presenter.present_collection(object, self)
else
presenter.present(object, self)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment