Skip to content

Instantly share code, notes, and snippets.

@stevenharman
Last active May 24, 2017 17:17
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 stevenharman/d7e6dd7e517158e88fd15441d905b1e6 to your computer and use it in GitHub Desktop.
Save stevenharman/d7e6dd7e517158e88fd15441d905b1e6 to your computer and use it in GitHub Desktop.
A Lo-Fi View Model/Presenter Base Class for Rails Apps
# 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
# 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