我正在尝试创建一个休息服务客户端作为服务。这是我的服务:
class MyService
def self.call(method_name, *args)
send(method_name, args)
end
def useful_method
'id, name'
end
# some methods below
end
当我尝试调用没有任何参数的方法时,这不起作用。例如,这个:
MyService.call(:useful_method)
失败,因为useful_method
不期望参数。我的大多数方法都有参数,所以这在大多数情况下都有效。
我也试过这个版本:
class MyService
def self.call(*args)
send(args)
end
def useful_method
'id, name'
end
# some methods below
end
但这似乎不适用于任何带或不带参数的方法。
如何根据方法是否包含参数来创建类似于传递method_name
后跟参数或无参数的内容?
我想我已经看过这个here,但我无法找到这个来源。
以下是我收到的版本1错误:
irb(main):001:0> MyService.call(:useful_method)
ArgumentError: wrong number of arguments (given 1, expected 0)
以下是我收到的第2版错误:
irb(main):001:0> MyService.call(:useful_method)
TypeError: [:useful_method] is not a symbol nor a string
答案 0 :(得分:2)
怎么样
class MyService
def self.call(*args)
send(*args)
end
class << self
private
def useful_method
'id, name'
end
end
end
答案 1 :(得分:0)
您可以使用`send(method_name,* args)
将params发送到send
或强>
像这样定义服务:
class MyService
attr_reader :method_name, :args
def initialize(options = {})
# extract attributes
method_name = options[:method_name] || default_value
args = options[:args] || []
end
def call
send(method_name, *args)
end
end
并致电该服务
MyService.new(method_name: 'useful_method', args: [staff]).call
答案 2 :(得分:0)
您正在尝试从类(静态)方法调用某些实例方法。
您需要将send
调用到该类的实例。这应该有效:
class MyService
def self.call(method_name, *args)
new.send(method_name, args)
end
def useful_method(*args)
'id, name'
end
# some methods below
end