Deekor
Deekor

Reputation: 9499

Check if a string contains 'http://' and '.jpg'

Im new to Ruby and Rails so forgive me if this an easy question. Im trying to check when a user passes in an IMG url in my form, that it is a valid url. Here is my code:

if params[:url].include? 'http://' && (params[:url].include? '.jpg' || params[:url].include? '.png')

This returns and error. Is this is even the best way to go about it? What should I do differently? Thanks.

Upvotes: 3

Views: 3886

Answers (3)

the Tin Man
the Tin Man

Reputation: 160551

While regex will shorten the code, I prefer to not do such a check all in one pattern. It's a self-documentation/maintenance thing. A single regex is faster, but if the needed protocols or image types grow, the pattern will become more and more unwieldy.

Here's what I'd do:

str[%r{^http://}i] && str[/\.(?:jpe?g|png)$/]

Upvotes: 1

Phrogz
Phrogz

Reputation: 303224

if my_str =~ %r{\Ahttps?://.+\.(?:jpe?g|png)\z}i

Regex explained:

  • %r{...} — regex literal similar to /.../, but allows / to be used inside without escaping
  • \A — the start of the string (^ is just the start of the line)
  • http — the literal text
  • s? — optionally followed by an "s" (to allow https://)
  • :// — the literal text (to prevent something like http-whee.jpg)
  • .+ — one or more characters (that aren't a newline)
  • \. — a literal period (make sure this is an extension we're looking at)
  • (?:aaa|bbb) — allow either aaa or bbb here, but don't capture the result
  • jpe?g — either "jpg" or "jpeg"
  • png — the literal text
  • \z — the end of the string ($ is just the end of the line)
  • i — make the match case-insensitive (allow for .JPG as well as .jpg)

However, you might be able to get away with just this (more readable) version:

allowed_extensions = %w[.jpg .jpeg .png]
if my_str.start_with?('http://') &&
   allowed_extensions.any?{ |ext| my_str.end_with?(ext) }

Upvotes: 15

Pritesh Jain
Pritesh Jain

Reputation: 9146

@Phrogz answer is better,I just tried this with some ruby libs.

require 'uri'

extensions = %w( .jpg .jpeg .png )
schemes = %w( http https )
string = params[:url]

if (schemes.include?URI.parse(string).scheme) && (extensions.include?File.extname(string))

end

Upvotes: 3

Related Questions