简体   繁体   中英

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:

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:

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.create(how, data) # "how" is a, b, c

Wherever it lives, make it obvious–this makes it easy to extend, fix, and reason about.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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