Giter VIP home page Giter VIP logo

routing-filter's Introduction

Routing Filter

Build Status

Routing filters wrap around the complex beast that the Rails routing system is to allow for unseen flexibility and power in Rails URL recognition and generation.

As powerful and awesome the Rails' routes are, when you need to design your URLs in a manner that only slightly leaves the paved cowpaths of Rails conventions, you're usually unable to use all the goodness of helpers and convenience that Rails ships with.

This library comes with four more or less reusable filters and it is easy to implement custom ones. Maybe the most popular one is the Locale routing filter:

  • Locale - prepends the page's :locale (e.g. /de/products)
  • Pagination - appends page/:num (e.g. /products/page/2)
  • Uuid - prepends a uuid for authentication or other purposes (e.g. /d00fbbd1-82b6-4c1a-a57d-098d529d6854/products/1)
  • Extension - appends an extension (e.g. /products.html)

Requirements

Latest routing-filter (~> 0.7.0) only works with Rails >= 6.1. It should not be all too hard to get it working with plain Rack::Mount but I haven't had that usecase, yet.

For older Rails versions you have to use respective older releases.

Installation

Just install the Gem:

$ gem install routing-filter

The Gem should work out of the box with Rails 6.1 after specifying it in your application's Gemfile.

# Gemfile
gem 'routing-filter'

Usage

Once the Gem has loaded you can setup the filters in your routes file like this:

# in config/routes.rb
Rails.application.routes.draw do
  filter :pagination, :uuid
end

Filters can also accept options:

Rails.application.routes.draw do
  filter :extension, :exclude => %r(^admin/)
  filter :locale,    :exclude => /^\/admin/
end

The locale filter may be configured to not include the default locale:

# in config/initializers/routing_filter.rb
# Do not include default locale in generated URLs
RoutingFilter::Locale.include_default_locale = false

# Then if the default locale is :de
# products_path(:locale => 'de') => /products
# products_path(:locale => 'en') => /en/products

Testing

RoutingFilter should not be enabled in functional tests by default since the Rails router gets bypassed for most testcases. Having RoutingFilter enabled in this setup can cause missing parameters in the test environment. Routing tests can/should re-enable RoutingFilter since the whole routing stack gets executed for these testcases.

To disable RoutingFilter in your test suite add the following to your test_helper.rb / spec_helper.rb:

RoutingFilter.active = false

Running the tests

$ bundle install
$ bundle exec rake test

Filter order

You can picture the way routing-filter wraps filters around your application as a russian puppet pattern. Your application sits in the center and is wrapped by a number of filters. An incoming request's path will be passed through these layers of filters from the outside in until it is passed to the regular application routes set. When you generate URLs on the other hand then the filters will be run from the inside out.

Filter order might be confusing at first. The reason for that is that the way rack/mount (which is used by Rails as a core routing engine) is confusing in this respect and Rails tries to make the best of it.

Suppose you have a filter :custom in your application routes.rb file and an engine that adds a :common filter. Then Rails makes it so that your application's routes file will be loaded first (basically route.rb files are loaded in reverse engine load order).

Thus routing-filter will make your :custom filter the inner-most filter, wrapping the application first. The :common filter from your engine will be wrapped around that onion and will be made the outer-most filter.

This way common base filters (such as the locale filter) can run first and do not need to know about the specifics of other (more specialized, custom) filters. Custom filters on the other hand can easily take into account that common filters might already have run and adjust accordingly.

Implementing your own filters

For example implementations have a look at the existing filters in lib/routing_filter/filters

The following would be a skeleton of an empty filter:

module RoutingFilter
  class Awesomeness < Filter
    def around_recognize(path, env, &block)
      # Alter the path here before it gets recognized.
      # Make sure to yield (calls the next around filter if present and
      # eventually `recognize_path` on the routeset):
      yield.tap do |params|
        # You can additionally modify the params here before they get passed
        # to the controller.
      end
    end

    def around_generate(params, &block)
      # Alter arguments here before they are passed to `url_for`.
      # Make sure to yield (calls the next around filter if present and
      # eventually `url_for` on the controller):
      yield.tap do |result|
        # You can change the generated url_or_path here by calling `result.update(url)`.
        # The current url is available via `result.url`
      end
    end
  end
end

You can specify the filter explicitly in your routes.rb:

Rails.application.routes.draw do
  filter :awesomeness
end

(I am not sure if it makes sense to provide more technical information than this because the usage of this plugin definitely requires some advanced knowledge about Rails internals and especially its routing system. So, I figure, anyone who could use this should also be able to read the code and figure out what it's doing much better then from any lengthy documentation.

If I'm mistaken on this please drop me an email with your suggestions.)

Rationale: Two example use cases

Conditionally prepending the locale

An early use-case from which this originated was the need to define a locale at the beginning of a URL in a way so that

  • the locale can be omitted when it is the default locale
  • all the url_helpers that are generated by named routes as well as url_for continue to work in a concise manner (i.e. without specifying all parameters again and again)
  • ideally also plays nicely with default route helpers in tests/specs

You can read about this struggle and two possible, yet unsatisfying solutions here. The conclusion so far is that Rails itself does not provide the tools to solve this problem in a clean and dry way.

Expanding /sections/:id to nested tree segments

Another usecase that eventually spawned the implementation of this plugin was the need to map an arbitrary count of path segments to a certain model instance. In an application that I've been working on recently I needed to map URL paths to a nested tree of models like so:

root
+ docs
  + api
  + wiki

E.g. the docs section should map to the path /docs, the api section to the path /docs/api and so on. Furthermore, after these paths there need to be more things to be specified. E.g. the wiki needs to define a whole Rails resource with URLs like /docs/wiki/pages/1/edit.

The only way to solve this problem with Rails' routing toolkit is to map a big, bold /*everything catch-all ("globbing") route and process the whole path in a custom dispatcher.

This, of course, is a really unsatisfying solution because one has to reimplement everything that Rails routes are here to help with: regarding both URL recognition (like parameter mappings, resources, ...) and generation (url_helpers).

Solution

This plugin offers a solution that takes exactly the opposite route.

Instead of trying to change things between the URL recognition and generation stages to achieve the desired result it wraps around the whole routing system and allows to pre- and post-filter both what goes into it (URL recognition) and what comes out of it (URL generation).

This way we can leave everything else completely untouched.

  • We can tinker with the URLs that we receive from the server and feed URLs to Rails that perfectly match the best breed of Rails' conventions.
  • Inside of the application we can use all the nice helper goodness and conveniences that rely on these conventions being followed.
  • Finally we can accept URLs that have been generated by the url_helpers and, again, mutate them in the way that matches our requirements.

So, even though the plugin itself is a blatant monkey-patch to one of the most complex area of Rails internals, this solution seems to be effectively less intrusive and pricey than others are.

Etc

Authors: Sven Fuchs License: MIT

routing-filter's People

Contributors

akitaonrails avatar bricesanchez avatar clemens avatar dce avatar fwolfst avatar gauda avatar hasghari avatar hukl avatar jim avatar kevin-jj avatar kuroda avatar mattenat avatar matthewtodd avatar mjonuschat avatar mseppae avatar nebolsin avatar nevir avatar parndt avatar reiz avatar robertodecurnex avatar sbounmy avatar simi avatar tricknotes avatar zencocoon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

routing-filter's Issues

Won't work with Rails 6.1

I gave it a try on Rails 6.1 RC and figured that due to this change: rails/rails@437ab20, routing-filter gem won't work anymore. Sadly I don't have capacity to submit a PR, but at least this files need to be updated to support new object types (though most likely then it will break suppor for Rails <6.1):

  • lib/routing_filter/filter.rb
  • lib/routing_filter/adapters/rails.r

rails4 undefined local variable or method map

Hi All,

I am new to Rails. I tried to setup routing-filter with basic settings as per seen in the wiki/Localize_filter but go this error when starting the server:

/home/ubuntu/workspace/stuff/config/routes.rb:18:in block in <top (required)>': undefined local variable or methodmap' for #ActionDispatch::Routing::Mapper:0x0000000852e2e0 (NameError)

I have this in routes.rb:

Rails.application.routes.draw do
  map.filter 'locale'
  root 'static_pages#home'
  resources :categories
  resources :users, only: [:index, :show]
  resources :items
  devise_for :users
  get 'users/index'
  get 'users/show'
  resources :addresses do
     collection { post :import }
  end
end

I have set up routing.rb, application-controller.rb, environment.rb as per described in the Wiki.

wrong number of arguments (0 for 1)

I'm getting this error when using named_routes, this is the error trace:

$HOME/.bundle/ruby/1.8/gems/routing-filter-0.1.6/lib/routing_filter/filter.rb:11:in around_generate' $HOME/.bundle/ruby/1.8/gems/routing-filter-0.1.6/lib/routing_filter/filter.rb:11:insend'
$HOME/.bundle/ruby/1.8/gems/routing-filter-0.1.6/lib/routing_filter/filter.rb:11:in run' $HOME/.bundle/ruby/1.8/gems/routing-filter-0.1.6/lib/routing_filter/chain.rb:9:inrun'
(eval):3:in export_customers_url' (eval):3:inexport_customers_url'

This is the route.rb file

ActionController::Routing::Routes.draw do |map|
map.filter 'locale'

map.resources 'drafts', :path_prefix => 'invoices'

end

Everything was working fine with the version 0.0.5 of routing-filter installed as a plugin. Now I'm running the 0.1.6 gem version

Any advice about the problem?

I'm notice that if I use export_customers_url(:locale => I18n.locale) everything works but I know this isn't the way to deal with it

Thanks

Rails 4: around_generate sometimes not being called

With the following setup on rails 4, the around_generate method is not called for url helper methods such as products_path. It is being called as expected for an equivalent url_for call though.

module RoutingFilter
  class Translate < Filter
    ...
    def around_generate(params, &block)
      yield.tap do |result|
        puts 'should be called'
      end
    end
  end
end

MyApp::Application.routes.draw do
  filter :translate
  resources :products
end

products_path # => around_generate was not called
url_for(controller: 'products', action: 'index') # => around_generate was called

It seems to be related to optimized url helper methods, and the following monkey patch makes RoutingFilter behave as expected:

ActionDispatch::Routing::RouteSet::NamedRouteCollection::UrlHelper.class_eval do
  def self.optimize_helper?(route)
    false
  end
end

I don't understand the rails routing internals enough to know what's going on here, but hope there's a better solution than this monkey patch.

excluded? doesn't work with engines?

I am unsure if there's something wrong with the way I'm trying to get this done. I'm Ruby 2.0.0-p0, Rails 3.2.13, using Spree 1.3.2

Here's a snippet of my routes.rb:

Project::Application.routes.draw do

  filter :locale, exclude: /^\/admin/

  match '/faq' => "faqs#index", as: "faq"
  mount Spree::Core::Engine, at: '/'

end

In locale.rb, in the excluded?(url) method, url is always '/' for all Spree links. This means that all links of the admin area get the locale prepended even if I have admin excluded via regex.
I could put the filter inside Spree:

Spree::Core::Engine.routes.prepend do
  filter :locale, exclude: /^\/admin/
end

But that would prevent me from having routes outside Spree that get the "locale" treatment.

Devise "Not found. Authentication passthru."

# routes.rb
devise_for :users, controllers: { omniauth_callbacks: "omniauth_callbacks" }
filter :locale

I have "Not found. Authentication passthru." message from Devise with this filter, resolved by adding exclude:

filter :locale, exclude: /^\/users\/auth/

seems like routing-filter have some conflict with Devise, that's why it is looking as omniauth callbacks isn't defined, and we have message "Not found. Authentication passthru."

gem

It would be handy to have a gem, because of updates - new version of gem is visible in RubyGem source. Plugin version in project must be changed manually.

Gemcutter

So github will not build gems anymore. Why not to move to gemcutter?

Filter locale breaks default_url_options in tests (setting the Locale from URL Params)

In the Usage section, under Tests, it says that

RoutingFilter should not be enabled in functional tests by default.

And if I do so, it breaks the recommended way to Setting the Locale from URL Params, as described in the Rails I18n Guides.

Step to reproduce

rails _7.0.0_ new sample_app
rails generate scaffold Contact email
# run test, all passing
# add this gem
# configure it like described under [usage](https://github.com/svenfuchs/routing-filter#usage) section
# add `RoutingFilter.active = false` to test_helper.rb
# run tests again
rails test test/controllers/contacts_controller_test.rb
# it will fails with
Expected response to be a redirect to <http://www.example.com/contacts/980190963> but was a redirect to <http://www.example.com/en/contacts/980190963>.
Expected "http://www.example.com/contacts/980190963" to be === "http://www.example.com/en/contacts/980190963".

Expected behavior

When I add RoutingFilter.active = false to test_helper.rb all generated controller or route tests are passing.

or:

Add description in the README, how to use this gem with recommended way to setting the locale from URL params.

Actual behavior

In generated *ContactsControllerTest < ActionDispatch::IntegrationTest all assertions like assert_redirected_to contact_url(Contact.last) or assert_redirected_to contacts_url will fail.

Workaround

I find out, that instead of adding RoutingFilter.active = false to test_helper.rb I had to add RoutingFilter::Locale.include_default_locale = false.

Can't change locale in the URL?

Hello.

I installed and set up routing-filter as described on the gem documentation page.

It works for the default locale. For example, if I set up my default locale as :en,
the site is in English, and if I set my default locale as :zh, the site in Chinese.

But how can I make my site support BOTH languages?
when the default locale is :zh, I tried to change the URL by changing the "zh" to "en"
but the page is still in Chinese, not English.

Is this something not supported by this gem? If not, is there some other gem I can use?
Or have I not set up the routing-filter gem properly?

Thanks!
Zack

Why default locale is not fallen back to?

In my routes, I have:

  Rails.application.routes.draw do
    filter :pagination, :uuid, :locale
  end
 get 'lab' => 'experiments#lab'

however, I got routing error if I tried to visit a route of non-existing locale,
like for example: /ko/lab

any idea?

uninitialized constant RoutingFilter::Filter

When I use bundler with the latest code on rails 2.3.11 it gives me the following error.

Here is my sample filter /lib/routing_filter.rb:

module RoutingFilter
  class Country < Filter
    # remove the locale from the beginning of the path, pass the path
    # to the given block and set it to the resulting params hash
    def around_recognize(path, env, &block)
      country = nil
      path.sub! %r(^/(italy|france|spain)(?=/|$)) do country = $1; '' end
      returning yield do |params|
        params[:country] = country || 'italy'
      end
    end

    def around_generate(*args, &block)
      country = args.extract_options!.delete(:country) || 'italy'
      returning yield do |result|
        if country != 'italy'
          result.sub!(%r(^(http.?://[^/]*)?(.*))){ "#{$1}/#{country}#{$2}" }
        end 
      end
    end

  end
end

And my /config/routes.rb:

ActionController::Routing::Routes.draw do |main|
  filter :country
end

0.4.0.pre Does Not Do Proper Routing

I have finally had a chance to use the 0.4.0.pre version of the gem for Rails 4. However I am finding differences between this version and the one I currently use in my Rails 3 applications. I'm not sure if there are differences in the routing-filter gems or if the issue is with i18n changes in Rails 4.

Here is the code I have in both applications in application_controller.rb where I set the locale and create a cookie.

before_filter :set_locale

private
def set_locale
I18n.locale = (params[:locale] if params[:locale].present?) || cookies[:locale] || 'en'
cookies[:locale] = I18n.locale if cookies[:locale] != I18n.locale.to_s
end

Here is the code I have in config/routes.rb.

filter :locale

When I run my Rails 3 applications the locale appears in the URL link and my debug info when I click all my links. When I run my Rails 4 application the only time the locale appears in the link is when I click a link to set the locale. When I click all my other links (text or icon) the translations appear correctly but there is not a locale value in the URL or in the debug info.

Here is the code for my locale line in my header.

<%= link_to_unless_current "English", locale: "en" %> <%= link_to_unless_current "Español", locale: "es" %> <%= link_to_unless_current "Français", locale: "fr" %>

Again I'm not sure if the issue is with the 0.4.0.pre gem or if I need to make additional i18n changes in my Rails 4 application. From reading the i18n documentation I'm not seeing anything additional I need to do. There is no specific documentation about 0.4.0.pre so I assume I should be able to do what I am doing with the Rails 3 version of routing-filter.

Any help would be appreciated.

Didn't work on rails 4

If I try to run rails, I get this error:

samir@samir-VirtualBox:~/RubymineProjects/website$ rails s
/home/samir/.rvm/gems/ruby-2.1.0@website/gems/activesupport-4.0.3/lib/active_support/dependencies.rb:229:in `require': cannot load such file -- routing_filter/adapters/rails_4 (LoadError)
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/activesupport-4.0.3/lib/active_support/dependencies.rb:229:in `block in require'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/activesupport-4.0.3/lib/active_support/dependencies.rb:214:in `load_dependency'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/activesupport-4.0.3/lib/active_support/dependencies.rb:229:in `require'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/routing-filter-0.3.1/lib/routing_filter.rb:27:in `<top (required)>'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/activesupport-4.0.3/lib/active_support/dependencies.rb:229:in `require'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/activesupport-4.0.3/lib/active_support/dependencies.rb:229:in `block in require'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/activesupport-4.0.3/lib/active_support/dependencies.rb:214:in `load_dependency'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/activesupport-4.0.3/lib/active_support/dependencies.rb:229:in `require'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/routing-filter-0.3.1/lib/routing-filter.rb:1:in `<top (required)>'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/bundler-1.5.3/lib/bundler/runtime.rb:76:in `require'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/bundler-1.5.3/lib/bundler/runtime.rb:76:in `block (2 levels) in require'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/bundler-1.5.3/lib/bundler/runtime.rb:72:in `each'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/bundler-1.5.3/lib/bundler/runtime.rb:72:in `block in require'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/bundler-1.5.3/lib/bundler/runtime.rb:61:in `each'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/bundler-1.5.3/lib/bundler/runtime.rb:61:in `require'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/bundler-1.5.3/lib/bundler.rb:131:in `require'
    from /home/samir/RubymineProjects/website/config/application.rb:8:in `<top (required)>'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/railties-4.0.3/lib/rails/commands.rb:74:in `require'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/railties-4.0.3/lib/rails/commands.rb:74:in `block in <top (required)>'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/railties-4.0.3/lib/rails/commands.rb:71:in `tap'
    from /home/samir/.rvm/gems/ruby-2.1.0@website/gems/railties-4.0.3/lib/rails/commands.rb:71:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

In my Gemfile, I have:

gem 'routing-filter'

do I have install it from specific branch or repo?

Inherited_resources & Simple_form gems - undefined method _path when building form

I use inherited_resources and simple_form gems in my app.

Routes

MyApp::Application.routes.draw do
  filter :locale, :pagination,  :exclude => /^\/admin/
  resources :categories, :controller => "article/categories"
  root 'home#index'
end

my Controller

class Article::CategoriesController < ApplicationController
    inherit_resources
end

my Model

class Article::Category < ActiveRecord::Base
    translates :name, :description
    accepts_nested_attributes_for :translations
end

Form View

= simple_form_for resource do |f|
    = f.input :title 
    = f.input :description
    = f.button :submit

I get this error while loading view form

undefined method `article_category_path' for #<#<Class:0x00000002604a30>:0x000000046c86e0>

P.S. I'm using Rails_4

Please, can anyone help me to solve this?

Just switching locale

Using routing-filter, how would I stay on the same controller/action and just switch the locale?
Say I have some language buttons in my layout and want to switch the locale but always stay on the current page? Do I have to manipulate the current URL or is there a better way?

Old rails 3 branch

Hi Sven,

I think the old rails-3 branch is more confusing than useful now.

Keep up the great work,
Best regards,

  • Sébastien Grosjean - ZenCoocoon

Stack level too deep errors in Rspec (Rails 3.2.8)

I'm still feeling out the contours of this bug, but I wanted to put this out there to see if anyone had any initial thoughts.

I've written a custom filter, which is working great in the application, and works for any individual spec. However, if I run more than one spec at a time, the second spec dies with a "stack level too deep" error:

.../actionpack-3.2.8/lib/action_dispatch/routing/url_for.rb:102

It doesn't seem to matter what kind of spec - anything that uses routing can cause the error.

Is it possible that the routes are getting initialized repeatedly, and alias_method_chain is being applied over itself? Thanks for your help! (I'm still digging, and I'll update this issue if I find anything helpful or interesting.)

Support for case insensitive locales

For example it will both support zh-CN and zh-cn segments.

Here's the code we used for a project we are working on:

module CaseInsensitiveLocaleSupport
  # Extract the segment and find its supported version using the locales_map hash
  def extract_segment!(*)
    locale = super
    CaseInsensitiveLocaleSupport.locales_map.fetch(locale.downcase, locale).to_s if locale
  end

  # Setup a map for downcased locales
  def self.locales_map
    @locales_map ||= RoutingFilter::Locale.locales.map { |locale| [locale.to_s.downcase, locale]}.to_h
  end
end

class RoutingFilter::Locale
  # Update the regexp to ignore case
  @@locales_pattern = Regexp.new(locales_pattern.source, Regexp::IGNORECASE)

  prepend CaseInsensitiveLocaleSupport
end

As you can see it uses an additional hash that maps downcased locales symbols with their original versions. This will allow to fetch the right locale after extracting the URL segment.

If you think this could be useful we can provide a PR to include this support.

/cc @elia @masterkain

No route matches "/"

I'm trying to use the locale filter in a rails3 app. In the main everything seems to be working OK except my root deceleration is no longer recognised? I've also tried adding a simple matcher in case root_path/en is passed in but that's not matching either.

match '/:locale' => 'home#index'
root :to => "home#index"

I wondering if I'm missing here or whether anyone else is having this trouble!?

something wrong with filter route

Hi,
as a fresh newbie with RoR, I guess I'm missing some trivial step. Anyway, I'm using jRuby 1.4 on Rails 2.3.4, and after installing routing-filter gem that is well sitting in the built-in jRuby directory, I got that error message while launching my app:
=> Booting WEBrick
=> Rails 2.3.4 application starting on http://0.0.0.0:3000
JRuby limited openssl loaded. gem install jruby-openssl for full support.
http://jruby.kenai.com/pages/JRuby_Builtin_OpenSSL
/home/edel/.netbeans/6.8/jruby-1.4.0/lib/ruby/gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/builder.rb:175:in build': Illegal route: the :controller must be specified! (ArgumentError) from /home/edel/.netbeans/6.8/jruby-1.4.0/lib/ruby/gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/route_set.rb:309:inadd_route'
from /home/edel/.netbeans/6.8/jruby-1.4.0/lib/ruby/gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/route_set.rb:317:in add_named_route' from /home/edel/.netbeans/6.8/jruby-1.4.0/lib/ruby/gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/route_set.rb:57:inmethod_missing'
from /home/edel/Development/NetBeansProjects/biowizard/config/routes.rb:2
from /home/edel/.netbeans/6.8/jruby-1.4.0/lib/ruby/gems/1.8/gems/actionpack-2.3.4/lib/action_controller/routing/route_set.rb:226:in draw' from /home/edel/Development/NetBeansProjects/biowizard/config/routes.rb:1 from /home/edel/Development/NetBeansProjects/biowizard/config/routes.rb:145:inload'
from /home/edel/.netbeans/6.8/jruby-1.4.0/lib/ruby/gems/1.8/gems/activesupport-2.3.4/lib/active_support/dependencies.rb:145:in load_with_new_constant_marking' ... 16 levels... from /home/edel/.netbeans/6.8/jruby-1.4.0/lib/ruby/gems/1.8/gems/rails-2.3.4/lib/commands/server.rb:31:inrequire'
from /home/edel/.netbeans/6.8/jruby-1.4.0/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:31:in `require'
from script/server:3

My route.rb:

ActionController::Routing::Routes.draw do |map|
map.filter "locale"
map.connect "", :controller => "homepage", :action => "show"
...

Any idea about what I'm missing ?

Best regards,

Ed.

gem should include README.markdown and MIT-LICENSE files

The README file in GitHub says that this gem is licensed under the MIT license, which requires that the copyright notice and permission notices are distributed with the code. Unfortunately, the way the gemspec is written means that everyone who distributes the .gem file automatically violates the license by not including the copyright and the permission notice with the code. :)

Please update routing-filter.gemspec to include README.markdown and MIT-LICENSE in s.files.

:include_default_locale ignored in routes.rb ?

It seems that passing the ":include_default_locale => false" parameter in routes.rb has no effect (ie. include_default_locale is always true).

In routes.rb, what does not work :
filter :locale, :include_default_locale => false
(maybe it is not the way it should be done)

Workaround (set the attribute directly):
filter :locale
RoutingFilter::Locale.include_default_locale = false

So, maybe the problem is : how to set the include_default_locale attribute.

Filter also on subdomains

Hi there,

I'm currently using your plugin in order to filter the subdomain and add it as a param value, which is kind of important in my case. The thing is, since only the path is being passed to the around_recognize filter, along with the env from the request, i have to parse the env Host myself in order to get get the subdomain, which is something that the request object already does. It would be kind of good to either get the whole request on the filter, or, if heavy, get the domain, subdomain, scheme, port, all of that. Lets say, i wanted to filter the language as a subdomain.

Is it so, or am i missing something?

Regards,
Tiago

current_page? does not consider locale

Example:

current_page?('/en/my/current/page') returns false even if '/en/my/current/page' is the current url.

current_page?('/my/current/page') returns true.

Rails 3.0.3 issue with locale filter

Hi, I just updated my bundle to use Rails 3.0.3 and I'm getting errors everytime I use route helper paths.
Here's what I'm getting in the console:
http://pastebin.com/8X5qxBBP

It seems that routing-filter is treating my restaurant as a locale.
I think the error is here: /usr/lib/ruby/gems/1.8/gems/routing-filter-0.2.2/lib/routing_filter/filters/locale.rb:68

Everything works with Rails 3.0.0 and 3.0.1 .
I'm using routing-filter 0.2.2.

Please let me know if you need any more details.

Thanks

Routing Error instead of fallback to en

if I do:

http://lvh.me:3000/br/lab

where br language is not added, I get error:

Routing Error
br/lab

Rails.root: /Users/Apple/Documents/projects/my_idea_project

Application Trace | Framework Trace | Full Trace
app/controllers/application_controller.rb:74:in `routing_error'
lib/rack/seoredirect.rb:20:in `call'

How to force en locale at missing locales in the route? ex: /en/lab when br is missing

I am using version 0.6.0 with rails 4.2, please advice!

I'm not able to make a custom filter work

Hi there.

I'm trying to build a custom filter for our dynamic (and multilingual) URLs. For the moment I'm just playing around to see what can I do and then design them all.

Now, one of our URLs is '/courses/search_results?course_type=5'

course_type 5 corresponds to 'Course'. I'm trying to convert the above URL to something like '/courses/search_results/Course' but I cannot make it work. This is what I've tried:

module RoutingFilter
  class Theme < Filter
    THEME_SEGMENT = %r((Course)?$)

    def around_recognize(path, env, &block)
      course_type = extract_segment!(THEME_SEGMENT, path)
      yield.tap do |params|
        params[:course_type] = CourseType.find_by_name(course_type) if course_type
      end
    end

    def around_generate(params, &block)
      course_type_id = params.delete(:course_type)
      course_type_name = CourseType.find(course_type_id).name if course_type_id
      yield.tap do |result|
        append_segment!(result, "#{course_type_name}") if course_type_name
      end
    end

  end
end

I tried to debug from extract_segment! definition:

      def extract_segment!(pattern, path)
        path.sub!(pattern) { $2 || '' }
        path.replace('/') if path.empty?
        $1
      end

This is how pattern and path (after calling sub!) look like:

pattern: //courses/search_results/(Course)/
path: "/courses/search_results/"

As I understand, that URL ("/courses/search_results/") should be recognized, but instead I got this error:

image

Thanks!

Locale filter generating incorrect paths when app deployed to a sub-uri

Hello, there.

I'm currently trying to use the locale filter in an application of mine. I'm using rails 3.0.0 and routing-filter 0.2.0. I'm deploying using Phusion Passenger.

The application is deployed to a sub-uri, for example:

http://example.com/foo

The problem is that every url that is generated from the standard rails helpers does not take into account that sub-uri and instead of /foo/en/articles/, generates paths like /en/foo/articles/, which promptly break, since my apache/nginx can find nothing there.

There is no problem with recognition, if I enter the url http://example.com/foo/en/articles, the routing filter recognizes it.

From what I understood while poking around, recognition is probably not a problem, since it has the full request and can find the real root of the application. However, generation works on pure option hashes and I can either tweak those, or manupulate the resulting string. In the localization filter in particular, generating seems to call prepend_segment which is defined as

url.sub!(%r(^(http.?://[^/]*)?(.*))) { "#{$1}/#{segment}#{$2 == '/' ? '' : $2}" }

This works just fine in general, but doesn't do the right thing for a sub-uri deployment.

Unfortunately, I'm not very knowledgeable about the rails internals, so I have no idea what I could work with in that filter. If I had access to the current request, I could probably extract the prefix from that and shave it off from the string, but I'm not sure if that's even possible.

Regards, Andrew.

Locale selector

Once i running with routing-filter, what is the best way to change locale in views?

Example:
Chose Languge: English | Español | French

How i can accomplish this?

I have this in application_controller.rb
def set_user_language
I18n.locale = logged_in? ? current_user.profile.language.to_s : request.env['rack.locale']
end

I look in user's preferences and browser's preferences but i want to display links with languages

New release ?

Hello,

Rails 5 is around the corner and this PR is already merged : #60

Could you release a new gem version ?

Set :include_default_locale to true ignored

Hi!

I use gem version 0.5.0 and rails 4.3.2. If I set RoutingFilter::Locale.include_default_locale = true (in config/initializers/routing_filter.rb) in the response header the url is without locale. Any idea how to include locale in the response header url?

The request has localhost:3000/en/test but if I print out request.url in the controller action, I get localhost:3000/test! Why?

Doesn't work in Rails 3.2.0.rc1!

I get this lovely error:

/Users/parndt/.rvm/gems/ruby-1.9.3-p0/gems/routing-filter-0.2.4/lib/routing_filter/adapters/rails_3.rb:17:in 'filters': undefined method 'filters' for #Journey::Routes:0x007fa7b5ad2d98 (NoMethodError)

Reload the filters in development

How to make the filters refresh in development?

Restarting the rails 3 app works but it is slow. The code with the filters is in rails engine, maybe this is preventing rails to reload the filters.

Avoiding duplicate content SEO penalty

This routing filter gem has proven a real gem for us over the years, and have allowed us to build a hugely complex multi-lingual and multi-regional, multi-store platform which never seems to miss a beat. It's been great to be able to accept requests both with and without a country prefix, and transparently send the user to the best matching content based on their location and language settings. It really is super awesome. But our clients have been complaining that they get penalised by google search engines since the same content is available on both /somepage and /DE/somepage, which makes sense I guess, though I always used to think this was a huge bonus; for example you can share a link to a product which automagically takes anyone who follows it to the correct language, currency and availability for that product in their region, while still allowing country specific URLs to always take you to the same store/currency - but google search engines disagree.

Now I'm tasked with finding a way to turn every request for a page that doesn't have a country prefix into a permanent redirect to the corresponding page with country (regardless of whether this might result in a 404), without breaking anything else. But how? Since the routing filter has modified the request.original_fullpath I cannot look at this to determine whether a country was given or not, and I cannot set up the redirect inside the routing filter itself. Furthermore, the redirect cannot be done at the proxy either, since we need access to the platform configuration and database to determine whence to send the user. Only a redirect done by the Rails platform has any chance of getting them to the right place. I've spent quite some time scratching my head over this but cannot find an angle. Help?

How to use filter in a block?

Hi! I want to use filter in routes.rb in a block, so that I can filter only for some routes the locale:

Rails.application.routes.draw do
  filter :locale do
    get '/home', ...
    get '/help', ...
  end
end

So, the idea comes from gem route_translator where I can do:

Rails.application.routes.draw do
  localized do
    get '/home', ...
    get '/help', ...
  end
end

How can I do that?

Rails 3 rack-mount optimization doesn't work for constraints

It seems that the monkeypatches for the rack-mount optimizations don't work properly when using constraints in routes.

See this gist: https://gist.github.com/705804

URLs with subdomains are recognized correctly but not URLs without subdomains. As soon as I comment out the code generation stuff in routing filter, recognition works (but obviously routing filter doesn't work anymore).

I'm not 100% this is a problem specific to the constraints method – it could affect other aspects of routing, too.

Not working with Rails 3

/home/micha/.rvm/gems/ree-1.8.7-2010.01/gems/activesupport-3.0.0.beta3/lib/active_support/dependencies.rb:440:in `load_missing_constant': ActionDispatch::Routing is not missing constant Mapper! (ArgumentError)

can be fixed with:

klass = if ActionPack::VERSION::MAJOR >= 3
  ActionDispatch::Routing::DeprecatedMapper
else
  ActionController::Routing::RouteSet::Mapper
end


# allows to install a filter to the route set by calling: map.filter 'locale'
klass.class_eval do

next errors are strangerer.... good luck with them :D

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.