Last active
August 29, 2015 13:58
-
-
Save tlux/9940400 to your computer and use it in GitHub Desktop.
Presenter Pattern on Rails, a lightweight alternative for Draper (https://github.com/drapergem/draper)
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 Presenter | |
| class_attribute :presenter_options, instance_accessor: false | |
| self.presenter_options ||= {} | |
| attr_reader :object, :template, :options | |
| def initialize(object, template, options = {}) | |
| @object = object | |
| @template = template | |
| @options = options.reverse_merge(self.class.presenter_options) | |
| end | |
| def self.presents(name, options = {}) | |
| self.presenter_options = options | |
| define_method name do | |
| @object | |
| end | |
| end | |
| def inspect | |
| "#<#{self.class.name} object: #{object.inspect}>" | |
| end | |
| def method_missing(method_name, *args, &block) | |
| if template and template.respond_to?(method_name) | |
| template.send(method_name, *args, &block) | |
| else | |
| super | |
| end | |
| end | |
| def respond_to_missing?(method_name, include_private = false) | |
| (template and template.respond_to?(method_name, include_private)) or super | |
| 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
| module PresenterHelper | |
| def present(object, *args) | |
| options = args.extract_options! | |
| klass = args.first || begin | |
| if object.is_a?(ActiveRecord::Relation) | |
| "#{object.klass.name.pluralize}Presenter".constantize | |
| else | |
| "#{object.class}Presenter".constantize | |
| end | |
| end | |
| presenter = klass.new(object, self, options) | |
| if block_given? | |
| yield presenter | |
| presenter | |
| else | |
| presenter.render | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment