我有这样的类命名空间:
module SocialSearch
module Scrapers
class TwitterScraper
# ...
end
end
end
我想在Scrapers
中创建一个方法,该方法将在命名空间内的所有类中进行扩展,但不会在每个类中手动执行include Scrapers
,因为它们位于Scrapers
名称空间。
谢谢!
答案 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