Prepend a character if string exists otherwise not - ruby-on-rails

I would like to prepend a '/' if the variable follow has a value otherwise if it is nil then keep it as nil
l2, follow = params[:all].split('/', 2)
follow = follow.nil? ? follow : "/#{follow}"
redirect_to "#{my_path(locale: locale, l2: l2)}#{rest}"
the params[:all] here could be a url path like
esp
esp/article/1
esp/article/1/author/1
EDIT:
My approach works but would like to know if there is a better way

follow.nil? ? follow : "/#{follow}"
Since Ruby has String#prepend method, the code can be refactored the following way:
follow && follow.prepend("/")
Or since Ruby 2.3 has safe navigation, it can be expressed even more concise:
follow&.prepend("/")

Related

lua sub string replace 2 pattern

due to using nginx lua (kong gateway)
would like to replace
from
{"body":"\r\n \"username\": \"sampleUser\",\r\n \"password\": \"samplePassword\",\r\n"}
to
{"body":"\r\n \"username\": \"sampleUser\",\r\n \"password\": \"***REDACTED***\",\r\n"}
from
username=sampleUser&password=samplePassword
to
username=sampleUser&password=***REDACTED***
from
"password" : "krghfkghkfghf"
to
"password" : "***REDACTED***"
i did try on sample https://stackoverflow.com/a/16638937/712063
local function replacePass(configstr, newpass)
return configstr:gsub("(%[\"password\"%]%s*=%s*)%b\"\"", "%1\"" .. newpass .. "\"")
end
it does not work, any recommended reference ?
maybe something like this:
local t = {
[[{"body":"\r\n \"username\": \"sampleUser\",\r\n \"password\": \"samplePassword\",\r\n"} ]],
[[username=sampleUser&password=samplePassword]],
[["password" : "krghfkghkfghf"]]
}
local newpass ="***REDACTED***"
for k,example in pairs(t) do
res = example:gsub('(password[\\" :]+)(.-)([\\"]+)',"%1"..newpass.."%3")
res = res:gsub("(password=).+","%1"..newpass)
print(res)
end
out:
{"body":"\r\n \"username\": \"sampleUser\",\r\n \"password\": \"***REDACTED***\",\r\n"}
username=sampleUser&password=***REDACTED***
"password" : "***REDACTED***"
There's several things wrong with that at first sight.
1. You only check for =
In your test data you seem to have cases with key = value as well as key : value but your pattern only checks for =; replace that with [=:] for a simple fix.
2. You can't balance quotation marks
I don't know how you expect this to work, but [[%b""]] just finds the shortest possible string between two " characters, just as [[".-"]] would. If that's your intention, then there's nothing wrong with writing it using %b though.
3. Just don't
As I don't know the context, I can't say if this really is a bad idea or not, but it does seem like a very brittle solution. If this is an option, I would recommend considering the alternative and going with something more robust.
As for what a better alternative could look like, I can't say without knowledge of your requirements. Maybe normalizing the data into a Lua table and replacing the password key in a uniform way? This would make sure that the data is either sanitized, or errors during parsing.
Beyond that, it would help if you told us how it doesn't work. It's easy to miss bugs when reading someone elses code, but knowing how the code misbehaves can help a lot with actually spotting the problem.
EDIT:
4. You didn't even remove the brackets
You didn't even remove the [] from that other stack overflow answer. Obviously that doesn't work without any modifications.

How to Build regular expression pattern in rails

I am actually writing rails code where i want to check if
params[:name] = any character like = , / \
to return true or return false otherwise.
How do i build a regex pattern for this or if any other better way exists would help too .
sanitized = params[:name].scan(/[=,\/\\]/)
if sanitized.empty?
# No such character in params[:name]
else
# oops, found atleast 1
end
HTH
I don't know if it's achieved the status of "idiomatic", but I think the most compact way of achieving this in Ruby is with double !:
!!(params[:name] =~ /[=,\/\\]/)
as discussed in How to return a boolean value from a regex

Regex in Ruby: expression not found

I'm having trouble with a regex in Ruby (on Rails). I'm relatively new to this.
The test string is:
http://www.xyz.com/017010830343?$ProdLarge$
I am trying to remove "$ProdLarge$". In other words, the $ signs and anything between.
My regular expression is:
\$\w+\$
Rubular says my expression is ok. http://rubular.com/r/NDDQxKVraK
But when I run my code, the app says it isn't finding a match. Code below:
some_array.each do |x|
logger.debug "scan #{x.scan('\$\w+\$')}"
logger.debug "String? #{x.instance_of?(String)}"
x.gsub!('\$\w+\$','scl=1')
...
My logger debug line shows a result of "[]". String is confirmed as being true. And the gsub line has no effect.
What do I need to correct?
Use /regex/ instead of 'regex':
> "http://www.xyz.com/017010830343?$ProdLarge$".gsub(/\$\w+\$/, 'scl=1')
=> "http://www.xyz.com/017010830343?scl=1"
Don't use a regex for this task, use a tool designed for it, URI. To remove the query:
require 'uri'
url = URI.parse('http://www.xyz.com/017010830343?$ProdLarge$')
url.query = nil
puts url.to_s
=> http://www.xyz.com/017010830343
To change to a different query use this instead of url.query = nil:
url.query = 'scl=1'
puts url.to_s
=> http://www.xyz.com/017010830343?scl=1
URI will automatically encode values if necessary, saving you the trouble. If you need even more URL management power, look at Addressable::URI.

In Rails, how do I determine if two URLs are equal?

If I have two URLs in Rails, (whether they be in string form or URI objects) what's the best way to determine if they are equal? It seems like a fairly simple problem, but I need the solution to work even if one of the URLs is relative and the other is absolute, or if one of the URLs has different parameters than the other.
I already looked at What is the best way in Rails to determine if two (or more) given URLs (as strings or hash options) are equal? (and several other questions), but the question was pretty old and the suggested solution doesn't work the way I need it to.
Provided you have url1 and url2 being some string containing a URL :
def is_same_controller_and_action?(url1, url2)
hash_url1 = Rails.application.routes.recognize_path(url1)
hash_url2 = Rails.application.routes.recognize_path(url2)
[:controller, :action].each do |key|
return false if hash_url1[key] != hash_url2[key]
end
return true
end
1) convert URL to canonical form
In my current project I am using addressable gem in order to do that:
def to_canonical(url)
uri = Addressable::URI.parse(url)
uri.scheme = "http" if uri.scheme.blank?
host = uri.host.sub(/\www\./, '') if uri.host.present?
path = (uri.path.present? && uri.host.blank?) ? uri.path.sub(/\www\./, '') : uri.path
uri.scheme.to_s + "://" + host.to_s + path.to_s
rescue Addressable::URI::InvalidURIError
nil
rescue URI::Error
nil
end
Example:
> to_canonical('www.example.com') => 'http://example.com'
> to_canonical('http://example.com') => 'http://example.com'
2) compare your URLs: canonical_url1 == canonical_url2
UPD:
Does it work with sub-domains? - No. I mean, we cannot say that translate.google.com and google.com are equal. Of course, you can modify it depending on your needs.
Checkout the addressable gem and specifically the normalize method (and its documentation), and the heuristic_parse method (and its documentation). I've used it in the past and found it to be very robust.
Addressable even handles URLs with unicode characters in them:
uri = Addressable::URI.parse("http://www.詹姆斯.com/")
uri.normalize
#=> #<Addressable::URI:0xc9a4c8 URI:http://www.xn--8ws00zhy3a.com/>

Need to make this expression shorter in ruby on rails 3

I need to make my code more compact. I have the following code:
params[:investor][:profit] = params[:investor][:profit].nil? ? nil : params[:investor][:profit].gsub(/\D/, '')
Basically what it does - it formats profit value from params to contain only digits, and if it was nil - just keep it nil...Is there any way to make it shorter.
You could tighten it down a little bit like so:
params[:investor][:profit].gsub!(/\D/, '') unless params[:investor][:profit].nil?
You could use the #try method from active_support:
params[:investor][:profit].try(:gsub!, /\D/, '')
um
p = params[:investor][:profit]
p = p.nil? ? nil : p.gsub(/\D/,'')
params[:investor][:profit] &&= params[:investor][:profit].gsub(/\D/, '')
If the value of params[:investor][:profit] is nil, this will evaluate to nil && .... Since nil is false, it will stay at nil, otherwise do the gsub.
I think it is heads up with the try solution mentioned in another solution. Choosing one over the other comes down to personal taste. I like the &&= solution because it's ruby instead of a rails convenience method and you do not need to "encrypt" what you really want to do in the try method's parameters.
params[:investor][:profit].gsub!(/\D/, '') if params[:investor][:profit]
or what I almost always use:
params[:investor][:profit].gsub!(/\D/, '') rescue nil
prof = params[:investor][:profit]
prof.gsub!(/\D/,'') if prof

Resources