1

How can I parse the params from a custom URL?

Lets say I have a User class that implements a to_param and a from_param method and I have a backend admin where a "customer" can insert an URL from a user (profile) page (e.g. http://localhost:3000/users/JohnDoe-123security456-123 where 123 is the ID).

Is it possible to generate a custom params object or something similar to parse the id from the url? My goal is to reuse the existing logic instead of creating another regex.

I know I could do something like: "http://localhost:3000/users/JohnDoe-123security456-123/custom_action?abc=def".gsub(/^.*\/users\//, '').gsub(/\/.*$/,'') (or something more suffisticated) to get the id.

Here is the pseudocode of what I try to achieve.

class User < ActiveRecord::Base
  def to_param
    "#{name}-#{security-token}-#{id}"
  end

  def self.id_from_param(param_id)
    param_id.to_s.gsub(/.*-/,'')
  end
end

class AdminUserController < ActionController::Base
  def search
    url = params[:url]
    parsed_params = some_method_that_extracts_the_params_from_url(url) # (1)
    user_id = User.id_from_param(parsed_params[:id])
  end
end
6
  • 1
    I don't understand what you're trying to do, you already have a method to get the ID from the parameter. Just call user_id = User.id_from_param(params[:id]) where params[:id] == "JohnDoe-123security456-123". Commented Dec 6, 2013 at 11:55
  • Assume that I get called like this: http://localhost:3000/admin/search?url=http://localhost:3000/users/JohnDoe-123security456-123. This way I do not have an ID. Commented Dec 6, 2013 at 13:17
  • Sending an entire URL as part of another URL seems highly inefficient to me. In order to get the id out of the URL, surely you could parse the URL to extract the data you need before using it? Commented Dec 6, 2013 at 14:49
  • yeah, why is that url being sent like that in the first place? Commented Dec 6, 2013 at 15:09
  • This is not part of the question, but here it is. Sometimes support staff gets urls to profiles of users and it is easier to copy paste the url into a form instead of handpicking the id. This is a requirement for me. But the question is still: is it possible to use the rails routing to get the params from a given url. Commented Dec 6, 2013 at 21:47

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.