gpt4 book ai didi

ruby/将参数传递给动态创建的类

转载 作者:太空宇宙 更新时间:2023-11-03 16:12:32 25 4
gpt4 key购买 nike

可能还有许多其他更好的方法;但有以下代码:

class ApplicationService
def self.build(*args, &block)
new(*args, &block).build
end
end

class BaseClass; end

class Fetcher < ApplicationService
attr_reader :resource_name

def initialize(resource_name)
@resource_name = resource_name
end

def build
resource_name = @resource_name

Class.new(BaseClass) do
@@resource_name = resource_name

class << self
def all
"http://some.remote.resource/#{@@resource_name}/all"
end
end
end
end
end


为了在 self.all 方法中有初始的 resource_name,我想到了定义 @@resource_name = resource_name。我完全不确定这是否是个好方法。

我希望能够使用这样的“生成器”,以提供以下接口(interface):

## In some kind of initializers :
Xyz = Fetcher.build('xyz')

## Final use :
Xyz.all

是否有更好的模式来动态创建类,同时在创建此类时传递参数?

最佳答案

不清楚您为什么要首先创建该类。如果有充分的理由,我的回答有点无效。

您可以使用“标准”OOP 技术并使用实例来获得所需的行为

class Fetcher
def initialize(resource_name)
@resource_name = resource_name
end

def all
"http://some.remote.resource/#{@resource_name}/all"
end
end

xyz_fetcher = Fetcher.new('xyz')
xyz_fetcher.all

否则,我猜你的代码或多或少就是你会/应该做的。只是,我会让 Fetcher 类充当单例(不使用 Fetcher 的实例):

class Fetcher < ApplicationService
# make a singleton by privatizing initialize (read this up somewhere else)

def self.build(resource_name)
Class.new(BaseClass) do
@@resource_name = resource_name

class << self
def all
"http://some.remote.resource/#{@@resource_name}/all"
end
end
end
end
end

然后

Xyz = Fetcher.build('xyz')
Xyz.all

现在,你有了 ApplicationService 的东西,它或多或少地实现了这一点(并传递了一个 block ),所以我们读者可能错过了大局的某些部分......请澄清这是否是情况。

除了单例化之外,您还可以使用模块来代替(感谢@max 的评论)。

关于ruby/将参数传递给动态创建的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58569750/

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