Sha256: 50256f5eef32e9c8cf122fa7f0c4f15c59693c1dd59ca56d5534691b2f94da8b

Contents?: true

Size: 1.33 KB

Versions: 1

Compression:

Stored size: 1.33 KB

Contents

require 'routing_filter/base'

module RoutingFilter
  class ForceExtension < Base
    attr_reader :extension, :exclude

    def initialize(*args)
      super
      @extension ||= 'html'
      @exclude = %r(^(http.?://[^/]+)?\/?$) if @exclude.nil?
    end

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

    def around_generate(*args, &block)
      returning yield 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)
        !(url.blank? || excluded?(url) || mime_extension?(url))
      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
      
      def append_extension!(url)
        url.replace url.sub(/(\?|$)/, ".#{extension}\\1")
      end

      def append_page!(url, page)
        url.replace "#{url}/pages/#{page}"
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
strikeroff-routing-filter-0.1.0 lib/routing_filter/force_extension.rb