Ruby命名空间mixin方法

时间:2015-01-09 23:35:28

标签: ruby

我有这样的类命名空间:

module SocialSearch
  module Scrapers
    class TwitterScraper
      # ...
    end
  end
end

我想在Scrapers中创建一个方法,该方法将在命名空间内的所有类中进行扩展,但不会在每个类中手动执行include Scrapers,因为它们位于Scrapers名称空间。

谢谢!

2 个答案:

答案 0 :(得分:1)

SocialSearch::Scrapers.constants.each do
  |k| k = SocialSearch::Scrapers.const_get(k)
  k.extend(SocialSearch::Scrapers)if k.instance_of?(Class)
end

SocialSearch::Scrapers.constants.each do
  |k| k = SocialSearch::Scrapers.const_get(k)
  k.include(SocialSearch::Scrapers)if k.instance_of?(Class)
end

答案 1 :(得分:0)

尝试使用继承:

class Scrapers
  # your common methods for all scrapers
end

class TwitterScraper < Scrapers
  # your twitter-related scraper setup; methods from Scrapers are visible here
end

class FacebookScraper < Scrapers
  # your twitter-related scraper setup; methods from Scrapers are visible here
end