gpt4 book ai didi

ruby-on-rails - 在 Ruby 的类级别添加 Enumerable mixin

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:22 26 4
gpt4 key购买 nike

我在我的 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

但是我如何在类级别而不是实例级别获得 Enumerable mixin。

即,当 include Enumerable 在类中时,Enumerable 方法的调用方式如下

company = Company.new
# which might iterate over the contents (users?) in a company
company.collect {|u| u}

但是我想打电话

# iterate over all companies and collect the managers
Company.collect {|c| User.managers}

并使用它

 Company.each

我觉得答案很明显,但今天早上我的元编程 foo 很弱。

最佳答案

您可以使用 include来自内部 class << self :

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]

此模式用于 Ruby 的 Prime class .写作 include包含一个模块对我来说看起来更干净,但你可以使用 extend以及(参见 Uri Agassi's answer)。

如果包含的模块依赖于 included 就会有所不同回调(Enumerable 没有):

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

作为noted by Зелёный你可以定义 each就在 block 内:(并且不使用 self )

class Foo
class << self
include Enumerable

def each
# ...
end
end
end

关于ruby-on-rails - 在 Ruby 的类级别添加 Enumerable mixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24651799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com