Question

I'm looking for a way to get the raw uninterpreted Rails route.

Say I have a route:

/data_model/23455-cooltitle/sub_models

When accessed I'd like to get the original route with parameters like:

/data_model/:model_id/submodels

Was it helpful?

Solution

I'm a little unclear what you want, but I'm going to assume you mean that given a String representing a path that maps onto one of our routes, you'd like to get back a String with the path segment parameters replaced by their identifying keys. You can do this as follows:

def uninterpret(path)
  path_params = Rails.application.routes.recognize_path(path)
  path_params.each do |key, value|
    path.sub!(value, ":#{key}")
  end
  path
end

I'm sure there are some edge cases unaccounted for there, but that should work for your standard resourceful route.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top