2013-05-09 21 views
0

有人可以幫我簡化我寫的這一行嗎?比難看的語法外,我肯定還有其它方法,除了EVAL以形成路徑重寫一個令人討厭的Ruby語法

return send("link_to", "(#{order_string[:direction]})" 
     ,eval("#{controller}_path(#{query_string})")) 

存在保證該

controller    = contacts 
query_string    = 'status: "ASC"' 
order_string[:direction] = "ASC" 

上面一行應導致(和它)

link_to "ASC",contacts_path(status: "ASC") 
+0

在哪些情況下這段代碼必須工作?爲什麼你必須使用'send'來調用'link_to'? – toro2k 2013-05-09 07:54:30

+0

這是一個提供排序鏈接的幫手,我知道一個相同的寶石,但我更願意將我的寶石依賴性降到最低。 – 2013-05-09 07:55:46

回答

2

作爲一個輔助方法中,你應該能夠做到:

return link_to(order_string[:direction], 
       send("#{controller}_path", query_string)) 

鑑於您的參數,這相當於:

return link_to('ASC', contacts_path(status: 'ASC')) 
+0

謝謝,它的工作原理。 – 2013-05-09 08:00:43

2

要避免使用eval,我會簡化link_to去,而不是使用路由方法。

return link_to order_string[:direction], 
       controller: controller, query_string 

,它會轉換成

return link_to 'ASC', controller: "contacts", status: 'ASC' 

,並在HTML

<a href="/contacts?status=ASC">ASC</a> 

另外,控制器旁邊,你可以添加actionid和Rails足夠聰明,做休息。

+0

+1不使用發送,將使用這一個 – 2013-05-09 08:06:11

+1

@amrnt我測試了你的代碼,它不起作用,它在Ruby 1.9中沒有語法上的有效性。它可能依賴於Ruby 2的關鍵字參數? – toro2k 2013-05-09 08:26:29

+0

@ toro2k它幾乎有效(它只是試圖使用1.9哈希語法)請參閱http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to的示例;但你是對的有一個小錯誤 – 2013-05-09 12:42:30