読者です 読者をやめる 読者になる 読者になる

routes.rb のrequirements のregexp に行頭記号とか使わないこと

舞波本を参考に

map.hoge 'foo/:bar/:baz', :controller => 'foo', :action => 'show', :requirements => {:date => /^\d{8}$/}

とすると、Regexp anchor characters are not allowed in routing requirements とかってエラー。


該当箇所のソースを眺めてみた。

actionpack-1.13.3/lib/action_controller/routing.rb

def assign_route_options(segments, defaults, requirements)
  route_requirements = {} # Requirements that do not belong to a segment

  segment_named = Proc.new do |key|
    segments.detect { |segment| segment.key == key if segment.respond_to?(:key) }
  end

  requirements.each do |key, requirement|
    segment = segment_named[key]
    if segment
      raise TypeError, "#{key}: requirements on a path segment must be regular expressions" unless requirement.is_a?(Regexp)
      if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
        raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
      end
      segment.regexp = requirement
    else
      route_requirements[key] = requirement
    end
  end

  defaults.each do |key, default|
    segment = segment_named[key]
    raise ArgumentError, "#{key}: No matching segment exists; cannot assign default" unless segment
    segment.is_optional = true
    segment.default = default.to_param if default
  end

  assign_default_route_options(segments)
  ensure_required_segments(segments)
  route_requirements
end


この部分で引っかかったのかな。

if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z}
  raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}"
end


ってことで、

map.hoge 'foo/:bar/:baz', :controller => 'foo', :action => 'show', :requirements => {:date => /\d{8}/}

これだけでも、8桁の数字以外にはマッチしないのでよしとする。