4

I'd like to have all my Rails routes treat dasherized paths as equivalent to underscored paths.

i.e. navigating to /foo-bars and /foo_bars both trigger the route resources :foo_bars.

Is that possible?

Asherlc
  • 1,111
  • 2
  • 12
  • 28

2 Answers2

1

will this help.

type_regexp = Regexp.new(["foo_bars", "foo-bars"].join("|"))
resources "foo_bars", path: type_regexp

if you have routes other than REST do this

resources "foo_bars", path: type_regexp do 
 member do 
  .....
 end
 collection do
  .....
 end
Athar
  • 3,258
  • 1
  • 11
  • 16
  • I'm looking for a solution that will apply to all routes automatically – Asherlc Jul 28 '15 at 18:50
  • i think Rails do not provide any normal/easy way to do it for all routes. what ever i have searched and implemented. this case will be handled explicitly. but if some one has some better solution. i would be glad to see it. – Athar Jul 28 '15 at 19:01
0

Just define Athar's answer as a lambda should be good enough IMHO.
Something like this:

custom_resources = ->(route_name) {
  string_route_name = route_name.to_s
  underscore_route_name = string_route_name.underscore
  dasherized_route_name = string_route_name.dasherize
  path_regexp = Regexp.new([
    Regexp.escape(underscore_route_name),
    Regexp.escape(dasherized_route_name),
  ].join('|'))
  # more custom code here if desired
  resources underscore_route_name, path: path_regexp
}

custom_resources.call(:foo_bar)
custom_resources.call(:another_foo_bar)

Warning: not actually tested

Curious Sam
  • 884
  • 10
  • 12