簡體   English   中英

是否有DRY方式可以使用相同的參數調用不同的Ruby方法?

[英]Is there a DRY way to call different Ruby methods with the same parameters?

我有這樣的代碼。

if star
  href = star_path( :"star[model]" => model.class, :"star[model_id]" => model.id ))
else
  href = unstar_path( :"star[model]" => model.class, :"star[model_id]" => model.id ))
end

如您所見,它正在調用star_path或unstar_path幫助器,但是具有相同的參數。 重復這樣的參數讓我感到很糟糕,感覺應該有更好的方法。

謝謝!

嘗試

options = { :"star[model]" => model.class, :"star[model_id]" => model.id }

if star
  href = star_path(options)
else
  href = unstar_path(options)
end

兩種方式:

  • 首先分配給變量

     path_options = :"star[model]" => model.class, :"star[model_id]" => model.id href = star ? star_path( path_options ) : unstar_path( path_options ) 
  • 使用自定義助手

     def custom_star_path( options = {} ) action = options.delete( :action ) || :star action == :star ? star_path( options ) : unstar_path( options ) end 

    並致電:

     custom_star_path( :action => (:unstar unless star), :"star[model]" => model.class, :"star[model_id]" => model.id ) 

    甚至更簡單:

     def custom_star_path( options = {} ) options.delete( :has_star ) ? star_path( options ) : unstar_path( options ) end custom_star_path( :has_star => star, :"star[model]" => model.class, :"star[model_id]" => model.id ) 
href =
send(
  star ? :star_path : :unstar_path,
  "star[model]".to_sym => model.class, "star[model_id]".to_sym => model.id
)

如何使用toggle_star_path幫助器

def toggle_star_path star, model
  options = { :"star[model]" => model.class, :"star[model_id]" => model.id }
  star ? unstar_path(options) : star_path(options)
end

然后在您看來,您只需致電:

toggle_star_path star, model

如果您想使用可變方法,那么我認為send是可行的方法。

根據文件

 send(symbol [, args...]) → obj
 send(string [, args...]) → obj

調用由符號/字符串標識的方法,並向其傳遞任何指定的參數。 如果名稱發送與obj中現有方法發生沖突,則可以使用__send__ 當方法由字符串標識時,該字符串將轉換為符號。

嘗試如下,簡單的兩行

options = { :"star[model]" => model.class, :"star[model_id]" => model.id }

href = star ? star_path(options) : unstar_path(options)

通過與此處發布的其他解決方案一起,我解決了這一問題:

options = {:"star[model]" => model.class, :"star[model_id]" => model.id}
href = send((star ? :unstar_path : :star_path ), options)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM