Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 扩展/修改库_Ruby On Rails_Ruby_Rmagick - Fatal编程技术网

Ruby on rails 扩展/修改库

Ruby on rails 扩展/修改库,ruby-on-rails,ruby,rmagick,Ruby On Rails,Ruby,Rmagick,我正在使用RMagick,我不喜欢一件事: 当我这样做时: Magick::ImageList.new(path) 路径必须始终为本地文件。因此,在我的代码中,我多次重复这一点: 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 我应该如何

我正在使用RMagick,我不喜欢一件事:

当我这样做时:

Magick::ImageList.new(path)
路径必须始终为本地文件。因此,在我的代码中,我多次重复这一点:

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

我应该如何管理这些代码以避免每次创建新的Magick::ImageList对象时重复?顺便说一下,我正在使用Rails。

我建议用您自己的类包装库,并在其中添加功能。这样做的另一个好处是将所有逻辑都放在一个地方,并允许您自定义功能以更好地适应您的域

也许是这样的:

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

我会建议重构上述代码,但我想向您展示一个具体的例子,说明我的建议(尤其是
else
子句o.o中的那一行)。

为什么不将重复的代码提取到一个模块中?使用一个模块或方法,但将其放在一个地方并重复调用。未能做到这一点会导致代码混乱。向我们展示触发
if
else
部分的
路径的示例。如果我这样做,如果我想调用Magick实例的方法怎么办?我需要在MySuperRadImageList中为所有Magick实例方法创建方法?是的,或者您可以使用Ruby的模块之类的东西,它提供了一种简单的方法来做到这一点。它还使代码中的内容非常清楚。