Class: ActionDispatch::Routing::Mapper

Inherits:
Object
  • Object
show all
Defined in:
lib/speaking_url/routing_extensions.rb

Instance Method Summary collapse

Instance Method Details

#speaking_url_resource(*resources) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/speaking_url/routing_extensions.rb', line 6

def speaking_url_resource(*resources)

  options = resources.extract_options!

  resources.map!(&:to_sym)

  resources.each do |sym|

    klass = Kernel.const_get(sym.to_s.classify) 

    current_address_constraint_class = Class.new do
      @klass = klass
      class << self; attr_reader :klass; end
      def matches?(request)
        r = self.class.klass.find_by_url(request.path)
        return false if r.nil?
        r.current_url == request.path
      end
    end

    old_address_constraint_class = Class.new do
      @klass = klass
      class << self; attr_reader :klass; end
      def matches?(request)
        r = self.class.klass.find_by_url(request.path)
        return false if r.nil?
        r.current_url != request.path
      end
    end

    controller = options[:controller] || klass.name.underscore.pluralize

    match "*path", :to  => "#{controller}#show", :constraints => current_address_constraint_class.new
    match "*path" => redirect{|p, req| klass.find_by_url(req.path).current_url}, :constraints => old_address_constraint_class.new

  end
end