Created
August 22, 2016 02:58
-
-
Save rreinhardt9/caa1e8a825cb5cf387d1929b5dcc9b6f to your computer and use it in GitHub Desktop.
A parent class for presenters to inherit from
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
# Presenter is a parent class for all presenters to inherit from | |
# | |
# A Presenter is a view model and should be used to format and collect data | |
# that is to be presented in a view. | |
class Presenter | |
include Rails.application.routes.url_helpers | |
# Initialize your presenter with an object and optional view context | |
# In your controller, you can pass in the `view_context` variable | |
def initialize(object, view = nil) | |
@object = object | |
@view = view | |
end | |
# Convenience method that allows you to alias the object name | |
# `presents :a_name` will alias @object to `a_name` | |
def self.presents(name) | |
define_method(name) do | |
@object | |
end | |
end | |
private_class_method :presents | |
private | |
# If a method we call is missing, pass the call onto | |
# the object presented. If it's still not found, raise appropriate error. | |
def method_missing(m, *args, &block) | |
context = caller | |
@object.send(m, *args, &block) | |
rescue NoMethodError | |
raise NoMethodError, | |
"undefined method `#{m}' for #{self} and the presented #{@object}", | |
context | |
end | |
# v is an alias for the view context | |
def v | |
@view | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment