Last active
May 24, 2017 17:17
-
-
Save stevenharman/d7e6dd7e517158e88fd15441d905b1e6 to your computer and use it in GitHub Desktop.
A Lo-Fi View Model/Presenter Base Class for Rails Apps
This file contains 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
# app/model/view/view_model.rb | |
# A base class for other view models (a.k.a., presenters) | |
module View | |
class ViewModel < SimpleDelegator | |
BUILD_DEFAULT_CONTEXT = -> { View::DefaultViewContext.new } | |
def initialize(model, view_context: BUILD_DEFAULT_CONTEXT.call) | |
@view_context = view_context | |
super(model) | |
end | |
protected | |
def source | |
__getobj__ | |
end | |
private | |
attr_reader :view_context | |
alias_method :h, :view_context | |
def t(*args) | |
h.translate(*args) | |
end | |
end | |
end |
This file contains 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
# app/models/view/default_view_context.rb | |
module View | |
class DefaultViewContext < ActionView::Base | |
include Rails.application.routes.url_helpers | |
include ApplicationHelper | |
def initialize() | |
super(ActionController::Base.view_paths) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment