¿Add [""] to ruby string? - ruby-on-rails

How can I convert this:
https://myimage.com
to this in ruby?
["https://myimage.com"]
I've tried with join with no luck...
Thanks

It's not very clear what you're looking to accomplish. You can't really turn https://myimage.com into anything, since it is not valid Ruby syntax.
However, if you first have it as a string, then you can easily put it inside of an array like this:
url = 'https://myimage.com'
result = [url]
puts result.inspect
#=> ["https://myimage.com"]
Or if instead you want a string as your result, then here yah go:
url = 'https://myimage.com'
result = '["' + url + '"]'
puts result
#=> ["https://myimage.com"]

Related

Tidy long string in Ruby

I have a method in Ruby, which needs an API URL:
request_url = "http://api.abc.com/v3/avail?rev=#{ENV['REV']}&key=#{ENV['KEY']}&locale=en_US&currencyCode=#{currency}&arrivalDate=#{check_in}&departureDate=#{check_out}&includeDetails=true&includeRoomImages=true&room1=#{total_guests}"
I want to format it to be more readable. It should take arguments.
request_url = "http://api.abc.com/v3/avail?
&rev=#{ENV['REV']}
&key=#{ENV['KEY']}
&locale=en_US
&currencyCode=#{currency}
&arrivalDate=#{check_in}
&departureDate=#{check_out}
&includeDetails=true
&includeRoomImages=true
&room1=#{total_guests}"
But of course there's line break. I tried heredoc, but I want it to be in one line.
I would prefer to not build URI queries by joining strings, because that might lead to URLs that are not correctly encoded (see a list of characters that need to be encoded in URIs).
There is the Hash#to_query method in Ruby on Rails that does exactly what you need and it ensure that the parameters are correctly URI encoded:
base_url = 'http://api.abc.com/v3/avail'
arguments = {
rev: ENV['REV'],
key: ENV['KEY'],
locale: 'en_US',
currencyCode: currency,
arrivalDate: check_in,
departureDate: check_out,
includeDetails: true,
includeRoomImages: true,
room1: total_guests
}
request_url = "#{base_url}?#{arguments.to_query}"
You could use an array and join the strings:
request_url = [
"http://api.abc.com/v3/avail?",
"&rev=#{ENV['REV']}",
"&key=#{ENV['KEY']}",
"&locale=en_US",
"&currencyCode=#{currency}",
"&arrivalDate=#{check_in}",
"&departureDate=#{check_out}",
"&includeDetails=true",
"&includeRoomImages=true",
"&room1=#{total_guests}",
].join('')
Even easier, you can use the %W array shorthand notation so you don't have to write out all the quotes and commas:
request_url = %W(
http://api.abc.com/v3/avail?
&rev=#{ENV['REV']}
&key=#{ENV['KEY']}
&locale=en_US
&currencyCode=#{currency}
&arrivalDate=#{check_in}
&departureDate=#{check_out}
&includeDetails=true
&includeRoomImages=true
&room1=#{total_guests}
).join('')
Edit: Of course, spickermann makes a very good point above on better ways to accomplish this specifically for URLs. However, if you're not constructing a URL and just working with strings, the above methods should work fine.
You can extend strings in Ruby using the line continuation operator. Example:
request_url = "http://api.abc.com/v3/avail?" \
"&rev=#{ENV['REV']}" \
"&key=#{ENV['KEY']}"

Regex extract substring ruby

"{\"status\":1,\"redirect\":\"/some/uri/uri2/index.html?post_login=80607979823520\",\"security_token\":\"/cpsess8233434446\"}"
I am getting this response as string and I need to extract security_token value.
I tried to convert the string to Hash by eval method.seems not worked and I need to do a regex match.
You can do this:
require 'json'
a = JSON.load "{\"status\":1,\"redirect\":\"/some/uri/uri2/index.html?post_login=80607979823520\",\"security_token\":\"/cpsess8233434446\"}"
p a["security_token"] #=> "/cpsess8233434446"
You need to parse the JSON data..
result = "{\"status\":1,\"redirect\":\"/some/uri/uri2/index.html?post_login=80607979823520\",\"security_token\":\"/cpsess8233434446\"}"
h = JSON.parse(result)
h['security_token'] # => "/cpsess8233434446"
You can either JSON.load the data and filter for ['security_token'] or use a .match(/security_token/) style regex expression.
I'd suggest the prior for future readability and code maintenance.

Removing a part of a URL with Ruby

Removing the query string from a URL in Ruby could be done like this:
url.split('?')[0]
Where url is the complete URL including the query string (e.g. url = http://www.domain.extension/folder?schnoo=schnok&foo=bar).
Is there a faster way to do this, i.e. without using split, but rather using Rails?
edit: The goal is to redirect from http://www.domain.extension/folder?schnoo=schnok&foo=bar to http://www.domain.extension/folder.
EDIT: I used:
url = 'http://www.domain.extension/folder?schnoo=schnok&foo=bar'
parsed_url = URI.parse(url)
new_url = parsed_url.scheme+"://"+parsed_url.host+parsed_url.path
Easier to read and harder to screw up if you parse and set fragment & query to nil instead of rebuilding the URL.
parsed = URI::parse("http://www.domain.extension/folder?schnoo=schnok&foo=bar#frag")
parsed.fragment = parsed.query = nil
parsed.to_s
# => "http://www.domain.extension/folder"
url = 'http://www.domain.extension/folder?schnoo=schnok&foo=bar'
u = URI.parse(url)
p = CGI.parse(u.query)
# p is now {"schnoo"=>["schnok"], "foo"=>["bar"]}
Take a look on the : how to get query string from passed url in ruby on rails
You can gain performance using Regex
'http://www.domain.extension/folder?schnoo=schnok&foo=bar'[/[^\?]+/]
#=> "http://www.domain.extension/folder"
Probably no need to split the url. When you visit this link, you are pass two parameters to back-end:
http://www.domain.extension/folder?schnoo=schnok&foo=bar
params[:schnoo]=schnok
params[:foo]=bar
Try to monitor your log and you will see them, then you can use them in controller directly.

Ruby regex find and replace a number inside a string

How would I find and replace '49' when '49' will be an unknown id, using ruby on rails?
str = "select * from clients where client_id = 49 order by registration_date asc"
str = str.gsub(/someRegExThatFinds49/, replacement_id) # <------ Here's the concept
Looking for a syntax and example that's correct. Thanks.
This would work, using a copy of the string:
new_str = str.gsub(/\d+/, replacement_id)
Or, if you prefer to do it in place (modifying the string directly)
str.gsub!(/\d+/, replacement_id)
ian.
unknown_id = 49
puts "hello4849gone".gsub(/#{unknown_id}/, "HERE") #=> hello48HEREgone
str = str.gsub(/49/, replacement_id)
Or use the self-updating version:
str.gsub!(/49/, replacement_id)
Also, check out Rubular which allows you to test out regular expressions.

URL manipulation: http://example.com/foo.jpg -> http://example.com/foo.preview.png

In rails I want to wrote some code to change this url string
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg
to
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.png
Should I use regular Expression to change it?
I'm new to Regexp, anyone can show me how to do this, and how to learn this stuff
thanks
If the extension is of fixed length, you're better off using string slicing.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
print url[0..-5] + ".preview" + url[-4..-1]
outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpg
Or if your extensions are of variable length you can use rindex() to find the start of the extension.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpeg"
dot_index = url.rindex(".")-1
print url[0..dot_index] + ".preview" + url[dot_index+1..-1]
outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpeg
If you must use a regex then do it like this:
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpeg"
print url.gsub(/\.(\w{2,4})$/, ".preview.\\1")
outputs
https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.preview.jpeg
If you're sure the file ends with .jpg, you can to
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
url.gsub(".jpg", ".preview.jpg")
Otherwise, you can get the filename, then append the extension.
url = "https://img.skitch.com/20101222-kg5chjx4jetgcdeaug46hi6jpk.jpg"
ext = File.extname(url)
url.gsub(ext, ".preview{ext}")
A string replace seems to be enough.
".jpg" -> ".preview.png"
Unfortunately I do not know ruby.
In python it'll be
new_url = url.replace(".jpg",".preview.png",1)
I think that it'll be similar in ruby. It seems to be sub() instead.
new_url = url.sub(".jpg",".preview.png")

Resources