有没有办法将自定义文件夹添加到"部分路径"?

Eri*_*edo 8 ruby-on-rails partial-views

我在一个名为的文件夹中有几个部分partials,我将它们渲染到我的视图中render 'partials/name_of_my_partial',这没关系.

无论如何,是否有可能以一种比我可以使用的方式设置东西render 'name_of_my_partial'并且rails自动检查这个partials文件夹?

现在,我有一个Missing partial错误.

num*_*407 10

在rails 3.0中这是一个挑战,但在调查中我发现在rails 3.1中,它们改变了路径查找的工作方式,使其更加简单.(我不知道他们改变了什么确切的版本,它可能早得多).

在3.1中,这是相对简单的,因为它们引入了一种向路径查找发送多个前缀的方法.它们通过实例方法检索_prefixes.

对于所有控制器,通过简单地覆盖它在基本控制器中(或者包含在基本控制器中的模块中,无论哪个),都很容易对其进行任意添加.

所以在3.1.x(其中lookup使用多个前缀):

class ApplicationController
  ...
  protected
  def _prefixes
    @_prefixes_with_partials ||= super | %w(partials)
  end
end 
Run Code Online (Sandbox Code Playgroud)

在此更改之前,单个前缀用于查找,这使得这更复杂.这可能不是最好的方法,但我过去解决了这个问题,试图通过我的"回退"前缀查找相同的路径来避免丢失模板错误.

在3.0.x(其中lookup使用单个路径前缀)

# in an initializer
module YourAppPaths
  extend ActiveSupport::Concern

  included do
    # override the actionview base class method to wrap its paths with your
    # custom pathset class
    def self.process_view_paths(value)
      value.is_a?(::YourAppPaths::PathSet) ?
        value.dup : ::YourAppPaths::PathSet.new(Array.wrap(value))
    end
  end

  class PathSet < ::ActionView::PathSet
    # our simple subclass of pathset simply rescues and attempts to
    # find the same path under "partials", throwing out the original prefix
    def find(path, prefix, *args)
      super
    rescue ::ActionView::MissingTemplate
      super(path, "partials", *args)
    end
  end
end

ActionView::Base.end(:include, YourAppPaths)
Run Code Online (Sandbox Code Playgroud)