Search code examples
ruby-on-railsrubyswitch-statementsend

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.


Solution

  • 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 (e.g., a send like this, a hash of Procs, 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.