Skip to content
This repository
tag: v0.1.7
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 76 lines (65 sloc) 1.862 kb
1 2 3 4 5 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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
# The Extension filter chops a file extension off from the end of the
# recognized path. When a path is generated the filter re-adds the extension
# to the path accordingly.
#
# incoming url: /de/products/page/1
# filtered url: /de/products
# params: params[:locale] = 'de'
#
# You can install the filter like this:
#
# # in config/routes.rb
# Rails.application.routes.draw do
# filter :locale
# end
#
# To make your named_route helpers or url_for add the pagination segments you
# can use:
#
# products_path(:locale => 'de')
# url_for(:products, :locale => 'de'))

module RoutingFilter
  class Extension < Filter
    attr_reader :extension, :exclude

    def initialize(*args)
      super
      @exclude = options[:exclude]
      @extension = options[:extension] || 'html'
    end

    def around_recognize(path, env, &block)
      extract_extension!(path) unless excluded?(path)
      yield(path, env)
    end

    def around_generate(params, &block)
      yield.tap do |result|
        url = result.is_a?(Array) ? result.first : result
        append_extension!(url) if append_extension?(url)
      end
    end

    protected
    
      def extract_extension!(path)
        path.sub!(/\.#{extension}$/, '')
        $1
      end
      
      def append_extension?(url)
        !(blank?(url) || excluded?(url) || mime_extension?(url))
      end
      
      def append_extension!(url)
        url.replace url.sub(/(\?|$)/, ".#{extension}\\1")
      end
      
      def blank?(url)
        url.blank? || !!url.match(%r(^/(\?|$)))
      end
      
      def excluded?(url)
        case exclude
        when Regexp
          url =~ exclude
        when Proc
          exclude.call(url)
        end
      end
      
      def mime_extension?(url)
        url =~ /\.#{Mime::EXTENSION_LOOKUP.keys.join('|')}(\?|$)/
      end
  end
end
Something went wrong with that request. Please try again.