了解rails中的路由方法

时间:2013-03-05 17:02:20

标签: ruby-on-rails routes

我是rails的新手,在理解我正在处理的项目中的一些代码时完全迷失了:

routes.rb,我有

ActionController::Routing::Routes.draw do |map|
...

  map.filter "repository_owner_namespacing", :file => "route_filters/repository_owner_namespacing"
...
end

我尝试了解如何在around_recognize中调用方法repository_owner_namespacing.rb。后一个文件就是这样开始的

require 'routing_filter/base'

module RoutingFilter
  class RepositoryOwnerNamespacing < Base
...
def around_recognize
...
似乎在routing_filter.rb中调用

around_recognize,其开头如下:

module RoutingFilter
  mattr_accessor :active
  @@active = true

  class Chain < Array


    def << (filter)
      filter.successor = last
      super
    end

    def run(method, *args, &final)
      RoutingFilter.active ? last.run(method, *args, &final) : final.call
    end
  end
end

# allows to install a filter to the route set by calling: map.filter 'locale'
ActionController::Routing::RouteSet::Mapper.class_eval do
  def filter(name, options = {})
    require options.delete(:file) || "routing_filter/#{name}"
    klass = RoutingFilter.const_get name.to_s.camelize
    @set.filters << klass.new(options)
  end
end
def filters
    @filters ||= RoutingFilter::Chain.new
end

...

和routoing_fiter / base.rb,有

module RoutingFilter
  class Base
    attr_accessor :successor, :options

    def initialize(options)
      @options = options
      options.each{|name, value| instance_variable_set :"@#{name}", value }
    end

    def run(method, *args, &block)
      successor = @successor ? lambda { @successor.run(method, *args, &block) } : block
      send method, *args, &successor
    end
  end
end

我的问题是我真的不知道'last'的设置位置(在filter.successor = last中),以及设置了@set的位置。我在代码的项目中找不到任何全面的跟踪信息。它是否与ruby或rails内置变量相对应? (顺便说一句,这个@set.filters << klass.new(options)对应什么?)

1 个答案:

答案 0 :(得分:1)

在您的代码中RoutingFilter::Chain扩展Arraylast方法为defined in Array。所以在这种情况下,它是添加到链中的最后一个过滤器。