Pregunta

I am using RMagick and I don't like one thing:

When I do:

Magick::ImageList.new(path)

path has always to be a local file. So, in my code I have many times repeating this:

if URI(path).host.nil?
  Magick::ImageList.new(path)
else
  url_image = open(path)
  image = Magick::ImageList.new
  image.from_blob(url_image.read)
end

How should I manage that code in order to avoid repeating everytime I want to create a new Magick::ImageList object? I am using Rails by the way.

¿Fue útil?

Solución

I would suggest wrapping the library with your own class, adding the functionality there. This has the added benefit of keeping the logic all in one place, and letting you customize the functionality to fit your domain better.

Perhaps something along these lines:

class MySuperRadImageList
  def self.open(path)
    image_list = if URI(path).host.nil?
                   Magick::ImageList.new(path)
                 else
                   Magick::ImageList.new.from_blob(open(path).read)
                 end
    self.new(image_list)
  end

  def initialize(image_list)
    # ...
  end
end

I would recommend refactoring the above code, but wanted to show you an concrete example of what I was suggesting (especially that line in the else clause o.O ).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top