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
Related
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("/")
I need to check if a string is valid image url.
I want to check beginning of string and end of string as follows:
Must start with http(s):
Must end by .jpg|.png|.gif|.jpeg
So far I have:
(https?:)
I can't seem to indicate beginning of string \A, combine patterns, and test end of string.
Test strings:
"http://image.com/a.jpg"
"https://image.com/a.jpg"
"ssh://image.com/a.jpg"
"http://image.com/a.jpeg"
"https://image.com/a.png"
"ssh://image.com/a.jpeg"
Please see http://rubular.com/r/PqERRim5RQ
Using Ruby 2.5
Using your very own demo, you could use
^https?:\/\/.*(?:\.jpg|\.png|\.gif|\.jpeg)$
See the modified demo.
One could even simplify it to:
^https?:\/\/.*\.(?:jpe?g|png|gif)$
See a demo for the latter as well.
This basically uses anchors (^ and $) on both sides, indicating the start/end of the string. Additionally, please remember that you need to escape the dot (\.) if you want to have ..
There's quite some ambiguity going on in the comments section, so let me clarify this:
^ - is meant for the start of a string
(or a line in multiline mode, but in Ruby strings are always in multiline mode)
$ - is meant for the end of a string / line
\A - is the very start of a string (irrespective of multilines)
\z - is the very end of a string (irrespective of multilines)
You may use
reg = %r{\Ahttps?://.*\.(?:png|gif|jpe?g)\z}
The point is:
When testing at online regex testers, you are testing a single multiline string, but in real life, you will validate lines as separate strings. So, in those testers, use ^ and $ and in real code, use \A and \z.
To match a string rather than a line you need \A and \z anchors
Use %r{pat} syntax if you have many / in your pattern, it is cleaner.
Online Ruby test:
urls = ['http://image.com/a.jpg',
'https://image.com/a.jpg',
'ssh://image.com/a.jpg',
'http://image.com/a.jpeg',
'https://image.com/a.png',
'ssh://image.com/a.jpeg']
reg = %r{\Ahttps?://.*\.(?:png|gif|jpe?g)\z}
urls.each { |url|
puts "#{url}: #{(reg =~ url) == 0}"
}
Output:
http://image.com/a.jpg: true
https://image.com/a.jpg: true
ssh://image.com/a.jpg: false
http://image.com/a.jpeg: true
https://image.com/a.png: true
ssh://image.com/a.jpeg: false
The answers here are quite good, but if you wanted to avoid using a complicated regex and communicate your intent more clearly to a reader, you could let URI and File do the heavy lifting for you.
(And since you're using 2.5, let's use #match? instead of other regex-matching methods.)
def valid_url?(url)
# Let URI parse the URL.
uri = URI.parse(url)
# Is the scheme http or https, and does the extension match expected formats?
uri.scheme.match?(/https?/i) && File.extname(uri.path).match?(/(png|jpe?g|gif)/i)
rescue URI::InvalidURIError
# If it's an invalid URL, URI will throw this error.
# We'll return `false`, because a URL that can't be parsed by URI isn't valid.
false
end
urls.map { |url| [url, valid_url?(url)] }
#=> Results in:
'http://image.com/a.jpg', true
'https://image.com/a.jpg', true
'ssh://image.com/a.jpg', false
'http://image.com/a.jpeg', true
'https://image.com/a.png', true
'ssh://image.com/a.jpeg', false
'https://image.com/a.tif', false
'http://t.co.uk/proposal.docx', false
'not a url', false
How to implement simple if else condition in rails
PHP : echo $params = isset($_POST['some_params']) ? $_POST['some_params'] : "";
RAILS : ??
Thanks,
You may want to look into Ruby Ternary operator: A good source is http://www.tutorialspoint.com/ruby/ruby_operators.htm
params[:some_params].present? ? 'a' : 'b'
another way of doing this is:
if params[:some_params].present?
....
else
....
end
There is one more operator called Ternary Operator. This first
evaluates an expression for a true or false value and then execute one
of the two given statements depending upon the result of the
evaluation. The conditional operator has this syntax:
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.
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.