Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.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中添加类级别的可枚举mixin_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 在Ruby中添加类级别的可枚举mixin

Ruby on rails 在Ruby中添加类级别的可枚举mixin,ruby-on-rails,ruby,Ruby On Rails,Ruby,我在Rails应用程序中使用postgres模式,因此没有明确的方法跨所有公司进行查询(用于我们自己的分析)。我想实现每个方法,迭代所有公司并适当地切换postgres模式 我想打电话: Company.each do |company| # do something in the context of each company end 但我还想获得一些其他可列举的方法,如在本例中获取所有公司的所有经理的collect: Company.collect do |company| Use

我在Rails应用程序中使用postgres模式,因此没有明确的方法跨所有公司进行查询(用于我们自己的分析)。我想实现每个方法,迭代所有公司并适当地切换postgres模式

我想打电话:

Company.each do |company|
  # do something in the context of each company
end
但我还想获得一些其他可列举的方法,如在本例中获取所有公司的所有经理的
collect

Company.collect do |company|
  Users.managers
end
目前,我有这个工作得很好

class Company < ActiveRecord::Base
  # ...

  def self.each(&block)
    Company.all.each do |company|
      if Schemas.include? company.subdomain
        # this changes to that company's schema so all queries are scoped
        Apartment::Database.switch company.subdomain

        yield company if block_given?
      end
    end
  end
但是我想打电话

# iterate over all companies and collect the managers
Company.collect {|c| User.managers} 
并有它的用途

 Company.each
我觉得答案是显而易见的,但我的元编程foo今天早上很弱。

将“包含可枚举”用于课堂使用


你可以在
类中使用
include
。这个问题对我来说有很多学习内容。仅供参考:我最初尝试用ActiveRecord类来做这件事。不要那样做!当您调用Company.count并且它不再调用ActiveRecord count方法来计算数据库行数时,您会遇到非常奇怪的失败。记住,可枚举模块真的很大,如果你赢了我的Ruby…-)你现在赢了我的红宝石+1为什么不将所有(
include
def
)都包装起来呢?接受这个答案(尽管我实际上选择了Uri答案),因为它解释得更详细了一点。谢谢
 Company.each
class Company
  extend Enumerable

  def self.each
    yield 'a'
    yield 'b'
    yield 'c'
  end
end

Company.inject(&:+)
# => "abc"
class Foo

  class << self
    include Enumerable
  end

  def self.each
    yield 1
    yield 2
    yield 3
  end
end

Foo.map { |x| x * 2 } # => [2, 4, 6]
module M
  def self.included(other)
    puts "included in #{other}"
  end
end

class Foo
  class << self
    include M
  end
end
#=> "included in #<Class:Foo>"

class Bar
  extend M
end
#=> nothing
class Foo
  class << self
    include Enumerable

    def each
      # ...
    end
  end
end