简体   繁体   中英

Construct a dynamic route path in Ruby

I want to construct a dynamic route path in ruby, something like this

    route = (a == a) ? "foo" : (b == b) ? "bar" : "default"
    link_to(event.try(:name), admin_"#{route}"_path('params goes here')

I very well know what I have tried is wrong. It should be done with dynamic method creations using class_eval or define_method I am not sure about that. Also, I am not familiar with those concepts. I can google but it would take much time to get a solution. Anyone, please help me solve this quickly. Thanks in advance.

This is pretty straightforward:

send("admin_#{route}_path", params)

You may want to wrap that up in a helper method to clean things up:

def admin_path_for_ab(a, b, params = nil)
  route =
    if (a == 'a')
       "foo"
    elsif (b == 'b')
       "bar"
    else
       "default"
    end

  send("admin_#{route}_path", params)
end

As a note, nesting ternaries ( x ? y : z ) is usually a bad idea, and a == a is always true.

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