在Ruby中,我可以在不使用模块名称的情况下访问模块方法吗?

时间:2015-01-09 18:25:09

标签: ruby methods module visibility

我有以下Ruby代码:

gallery = ViewableGallery.new(gallery_config.title, gallery_config.description, gallery_config.slug, \
  gallery_config.sources, gallery_config.upload_date, gallery_config.map_url, gallery_config.map_title, \
  gallery_config.year, viewable_photos).
  update_using( \
    GalleryGenerator.add_tabs_before_every_description_line(2), \
    GalleryGenerator.add_links_to_descriptions, \
    GalleryGenerator.for_each_photo(&GalleryGenerator.add_tabs_before_every_description_line(3)), \
    GalleryGenerator.for_each_photo(&GalleryGenerator.add_links_to_descriptions), \
    GalleryGenerator.for_each_photo(&GalleryGenerator.remove_final_empty_line_from_description))

如您所见,GalleryGenerator重复多次。我能以某种方式放弃吗?使用它无济于事:

include GalleryGenerator

供参考,模块本身:

module GalleryGenerator
  def self.add_tabs_before_every_description_line(how_many_tabs)
    lambda do |mutable_viewable_content|
      mutable_viewable_content.description = add_tabs_before_every_line(mutable_viewable_content.description, how_many_tabs)
      return mutable_viewable_content
    end
  end

# ...

  def self.for_each_photo(&update_function)
    return lambda do |mutable_viewable_gallery|
      mutable_viewable_gallery.photos.each do |mutable_viewable_photo|
        update_function.call(mutable_viewable_photo)
      end
      return mutable_viewable_gallery
    end
  end
end

1 个答案:

答案 0 :(得分:3)

只需包含模块并使方法实例方法不是类方法:

module GalleryGenerator
  def add_tabs_before_every_description_line(how_many_tabs)
    lambda do |mutable_viewable_content|
      mutable_viewable_content.description = add_tabs_before_every_line(mutable_viewable_content.description, how_many_tabs)
      return mutable_viewable_content
    end
  end

# ...

  def for_each_photo(&update_function)
    return lambda do |mutable_viewable_gallery|
      mutable_viewable_gallery.photos.each do |mutable_viewable_photo|
        update_function.call(mutable_viewable_photo)
      end
      return mutable_viewable_gallery
    end
  end
end