How Get some specific value from Rails string? - ruby-on-rails

I want to get some specific value from string of Rails like below these are two string.
1. "http://localhost:3000/admin/shops/assign_shoes?id=50&page=1"
2. "http://localhost:3000/admin/shops/assign_shoes?id=50"
I always need value of "id" which is "50". Don't matter how many parameters are in string
as query string.
Actually these strings are values of request.referer
Any efficient method?
Thanks

Here is one of the ways:
require 'uri'
require 'cgi'
uri = URI.parse("http://localhost:3000/admin/shops/assign_shoes?id=50&page=1")
# => #<URI::HTTP:0x000001018dc5c8 URL:http://localhost:3000/admin/shops/assign_shoes?id=50&page=1>
uri_params = CGI.parse(uri.query)
# => {"id"=>["50"], "page"=>["1"]}
uri_params["id"].first #=> "50" - NOTE: this will be a String!!
However, I'd prefer the answer which uses regular expressions.

Use regular expressions.
id = /\/admin\/shops\/assign_shoes\?id=(\d+)/.match(request.referer)[1]

There are several different ways to do this, the common way I know about is parsing the string using the URI class, and making use of the CGI class to extract the query params, like so:
uri = URI.parse(request.referer)
parsed_query = CGI::parse(uri.query).symbolize_keys
id_value = parsed_query[:id].first
Note the .first, as the values of the query params are resolved to arrays. Additionally, the keys are parsed in to strings, therefore I would include symbolize_keys for convenience and consistency.

Related

Unable to convert url params string to hash and then back to url string

Input is a params string (Input format cannot be changed)
something=1,2,3,4,5&something_else=6,7,8
Expected Output:
something=1,2,3,4,5&something_else=6,7,8
What I am doing:
params = 'something=1,2,3,4,5'
CGI::parse(params)
CGI.unescape(CGI.parse(params).to_query)
And I am getting this as output:
something[]=1,2,3,4,5
When I did CGI::parse(params)
I am getting this : {"something"=>["1,2,3,4,5"]}
which is wrong because it is not an array, something is a string which is "1,2,3,4,5" but it is being converted as array when I did CGI parse.
The reason I need to do CGI parse is because I need to manipulate the url PARAMS.
Is there any other possible way where I can convert it in the right way and maintain the params format?
The CGI module is a complete dinosaur and should probably be thrown in the garbage because of how bad it is, but for some reason it persists in the Ruby core. Maybe some day someone will refactor it and make it workable. Until then, skip it and use something better like URI, which is also built-in.
Given your irregular, non-compliant query string:
query_string = 'something=1,2,3,4,5&something_else=6,7,8'
You can handle this by using the decode_www_form method which handles query-strings:
require 'uri'
decoded = URI.decode_www_form(query_string).to_h
# => {"something"=>"1,2,3,4,5", "something_else"=>"6,7,8"}
To re-encode it you just call encode_www_form and then force unescape to undo what it's correctly doing to handle the , values:
encoded = URI.unescape(URI.encode_www_form(decoded))
# => "something=1,2,3,4,5&something_else=6,7,8"
That should get the effect you want.

check if string is base64

i may recieve these two strings:
base = Base64.encode64(File.open("/home/usr/Desktop/test", "rb").read)
=> "YQo=\n"
string = File.open("/home/usr/Desktop/test", "rb").read
=> "a\n"
what i have tried so far is to check string with regular expression i-e. /([A-Za-z0-9+\/]{4})*([A-Za-z0-9+\/]{4}|[A-Za-z0-9+\/]{3}=|[A-Za-z0-9+\/]{2}==$)/ but this would be very heavy if the file is big.
I also have tried base.encoding.name and string.encoding.name but both returns the same.
I have also seen this post and got regular expression solution but any other solution ?
Any idea ? I just want to get is the string is actually text or base64 encoded text....
You can use something like this, not very performant but you are guaranteed not to get false positives:
require 'base64'
def base64?(value)
value.is_a?(String) && Base64.strict_encode64(Base64.decode64(value)) == value
end
The use of strict_encode64 versus encode64 prevents Ruby from inadvertently inserting newlines if you have a long string. See this post for details.

Rails: Converting URL strings to params?

I know Rails does this for you, but I have a need to do this myself for examples. Is there a simple, non-private method available that takes a string and returns the hash of params exactly as Rails does for controllers?
Using Rack::Utils.parse_nested_query(some_string) will give you better results since CGI will convert all the values to arrays.
I found a way after a more intense Google search.
To convert url string to params:
hash = CGI::parse(some_string)
And (as bonus) from hash back to url string:
some_string = hash.to_query
Thanks to: https://www.ruby-forum.com/topic/69428
In model you can write a query like
def to_param
"-#{self.first_name}" +"-"+ "#{self.last_name}"
end
More info
http://apidock.com/rails/ActiveRecord/Base/to_param
It will generate a url like http://ul.com/12-Ravin-Drope
More firendly url you can consult
https://gist.github.com/cdmwebs/1209732

Replace "%20" with "-" in URL for rails

I'm developing a web application using rails.
For aesthetic purposes, i need to replace %20 with -
Before: http://localhost:3000/movies/2006/Apna%20Sapna%20Money%20Money
After: http://localhost:3000/movies/2006/Apna-Sapna-Money-Money
Is there anyway i can achieve this in rails?
You should use URI.parse to break it into pieces and then change only the path component:
require 'uri'
u = URI.parse(url)
u.path = u.path.gsub('%20', '-')
url = u.to_s
Just a simple gsub on the whole URL would probably work fine but a little extra paranoia might save you some confusion and suffering down the road. Also, if you're just replacing a literal string rather than a regular expression, you can use a String as the first argument to gsub and avoid some escaping issues:
The pattern is typically a Regexp; if given as a String, any regular expression metacharacters it contains will be interpreted literally, e.g. '\\d' will match a backlash followed by d, instead of a digit.
If your string is stored in the variable url you can use
url.gsub(/%20/, "-")
to return the string you want, or
url.gsub!(/%20/, "-")
to actually modify the value of url with the value you want.
https://github.com/FriendlyId/friendly_id
this is the best way to go about seo urls
You probably want to be saving "Apna-Sapna-Money-Money" within your Movies model as an attribute (I usually call these slugs). Then, to generate these, you might just need to replace spaces in the movie title with hyphens. Something like:
class Movie
before_create :generate_slug
private
def generate_slug
slug = title.gsub(" ", "-")
end
end
Then in your controller action you can simply do a Movie.find_by_slug!(params[:id]) call.
Basically, there should be no reason for users to ever arrive at a URL with %20 in it...

how to parse multivalued field from URL query in Rails

I have a URL of form http://www.example.com?foo=one&foo=two
I want to get an array of values ['one', 'two'] for foo, but params[:foo] only returns the first value.
I know that if I used foo[] instead of foo in the URL, then params[:foo] would give me the desired array.
However, I want to avoid changing the structure of the URL if possible, since its form is provided as a spec to a client application. is there a good way to get all the values without changing the parameter name?
You can use the default Ruby CGI module to parse the query string in a Rails controller like so:
params = CGI.parse(request.query_string)
This will give you what you want, but note that you won't get any of Rails other extensions to query string parsing, such as using HashWithIndifferentAccess, so you will have to us String rather than Symbol keys.
Also, I don't believe you can set params like that with a single line and overwrite the default rails params contents. Depending on how widespread you want this change, you may need to monkey patch or hack the internals a little bit. However the expeditious thing if you wanted a global change would be to put this in a before filter in application.rb and use a new instance var like #raw_params
I like the CGI.parse(request.query_string) solution mentioned in another answer. You could do this to merge the custom parsed query string into params:
params.merge!(CGI.parse(request.query_string).symbolize_keys)

Resources