简体   繁体   English

在Ruby中,有一种替代的,更优雅的方法来调用方法而不是'case - when'吗?

[英]In Ruby is there an alternative and more elegant way to call a method than 'case - when'?

In Rails 3.1, I want to create an embedded object by using a create method that accepts parameter data, but I am wondering if there is a more elegant way to do this than the case method below: 在Rails 3.1中,我想通过使用接受参数数据的create方法创建一个嵌入对象,但我想知道是否有比下面的case方法更优雅的方法:

def method_call(obj,data)
  case obj
  when 'a' then User.create_a(data)
  when 'b' then User.create_b(data)
  when 'c' then User.create_c(data)
  end
end

I would really like to do something like the following, but the this causes an error because of the data that I pass: 我真的想做类似下面的事情,但由于我传递的数据,这会导致错误:

def method_call(obj,data)
  User.send("create_#{obj}")(data)
end

Any suggestions? 有什么建议么? Thanks in advance. 提前致谢。

The send method takes the same parameters given to the method being called: send方法采用与被调用方法相同的参数:

User.send("create_#{obj}", data)

Whether or not this is the most elegant solution depends: I'd leave the decision-making process up to the User class, which could happen in a variety of ways (eg, a send like this, a hash of Proc s, etc.) A factory service is another alternative. 这是否是最优雅的解决方案取决于:我将决策过程留给User类,这可能以各种方式发生(例如,像这样的发送, Proc的哈希等。工厂服务是另一种选择。

User.create(how, data) # "how" is a, b, c

Wherever it lives, make it obvious–this makes it easy to extend, fix, and reason about. 无论它生活在哪里,都要明白 - 这使得它易于扩展,修复和推理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM