Asherlc
Asherlc

Reputation: 1161

Rails dasherize routes

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?

Upvotes: 4

Views: 617

Answers (2)

Curious Sam
Curious Sam

Reputation: 1299

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

Upvotes: 0

Athar
Athar

Reputation: 3268

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

Upvotes: 1

Related Questions