防止视图访问模型

Prevent view to access models

为了在大项目的视图中强制关注点分离并防止肮脏的黑客攻击,我想在视图中注入数据(例如通过控制器),然后视图将无法访问模型,或项目的任何 class(仅已注入的数据结构)。

有了Rails,我们如何防止视图中嵌入的Ruby代码访问项目的其他部分?

好的。这是它的坚果。 (此代码不完整,是为了指明方向,我删除了很多,所以你需要填写空白。)

首先,我创建了一个名为 ActsAs::Rendering 的模块。这提供了一个ActionView::Base的实例,这是在任何地方渲染的关键。

module ActsAs::Rendering
  private

    def action_view() @action_view ||= new_action_view end

    def new_action_view
      av = ActionView::Base.new
      av.view_paths = ActionController::Base.view_paths
      av.class_eval do
        include Rails.application.routes.url_helpers
        include ApplicationHelper
      end
      av
    end

    def method_missing(meth, *params, &block)
      if action_view.respond_to?(meth)
        action_view.send(meth, *params, &block)
      else
        super
      end
    end

    def render_partial(file_ref)
      render(partial: "#{file_ref}", locals: {presenter: self})
    end
end

然后,我创建了一个包含 ActsAs::Rendering:

PresenterBase
def PresenterBase
  include ActsAs::Rendering 

  class << self

    def present(args={})
      new(args).present
    end

  end # Class Methods

  #==============================================================================================
  # Instance Methods
  #==============================================================================================

    def initialize(args)
      @args = args
    end

  private

end

现在我创建了一个 Presenter class 来实现 present.

def FooPresenter < PresenterBase 

  #==============================================================================================
  # Instance Methods
  #==============================================================================================

    def present
      render_partial 'path/to/foo/partial'
      # or do a lot of other cool stuff.
    end

end

我的观点都以:

开头
- @presenter = local_assigns[:presenter] if local_assigns[:presenter]

现在,视图不再可以访问除它的展示者之外的任何内容。

* 注意 *

还有一点,但我必须运行出来。稍后更新。