class << self在构造内部创建方法的新实例背后的想法是什么?我知道方法被放在class << self块下以使它们成为类方法,但是创建方法本身的新实例意味着什么?
class foo
class << self
def bar(param)
new.bar(some_param)
end
end
end
class << self在构造内部创建方法的新实例背后的想法是什么?我知道方法被放在class << self块下以使它们成为类方法,但是创建方法本身的新实例意味着什么?
class foo
class << self
def bar(param)
new.bar(some_param)
end
end
end
我认为您试图描述的是一种方便的方法:
class FooService
def initialize
@bar= Bar.new
end
# this does the actual work
def call
results = @bar.do_some_work
results.each do
# ...
end
end
# this is just a convenient wrapper
def self.call
new.call
end
end
这使您可以调用FooService.call类方法,而不是使用FooService.new.call. 从这个简单的示例来看,它看起来并没有那么多,但它对于抽象出对象初始化(如服务对象)或将初始化器参数与方法参数组合起来非常有用。
class ApiClient
def initialize(api_key)
@api_key = api_key
end
def get(path)
# ...
end
def self.get(path, api_key: ENV['API_KEY'])
new(api_key).call(path)
end
end
ApiClient.get('foo')