簡體   English   中英

我怎樣才能重構這個Ruby和Rails代碼?

[英]How can I refactor this Ruby and Rails code?

我該如何重構這段代碼?

if env["rack.request.form_hash"] && env["rack.request.form_hash"]["authenticity_token"]
  env["rack.request.form_hash"]["authenticity_token"]=env["rack.request.form_hash"]["authenticity_token"].gsub("\r\n",'')
end
env["rack.request.form_hash"]["authenticity_token"] = env["rack.request.form_hash"]["authenticity_token"].gsub("\r\n",'') rescue nil

或者進行編輯

env["rack.request.form_hash"]["authenticity_token"].gsub!("\r\n",'') rescue nil

如果你有andand gem,你可以跳過檢查並直接進入:

env["rack.request.form_hash"]["authenticity_token"].andand.gsub("\r\n",'')

哈希索引似乎在任何地方都可以重用,也許你可以從那里開始。

   key1 = "rack.request.form_hash"
   key2 = "authenticity_token"
   env[key1] && env[key1][key2]

沒有什么聰明,但顯着縮短了界限。

像這樣的東西可以工作:

    env[key1][key2].gsub!('\r\n','') if env.has_key?(key1) && env[key1].has_key?(key2)

我建議:

if (rrf = env["rack.request.form_hash"]) && rrf_at = rrf["authenticity_token"] then rrf_at.gsub!("\r\n",'') end

或類似但更短的:

rrf_at.gsub!("\r\n",'') if (rrf = env["rack.request.form_hash"]) && rrf_at = rrf["authenticity_token"]

這是干,簡潔,不使用救援“黑客”;-D

而不是使用andandtry ,我會這樣做:

if env.fetch("rack.request.form_hash", {})["authenticity_token"].to_s.gsub("\r\n",'')

或者將to_hash添加到有用的NilClass方法( to_ato_sto_i等)的清單中:

class NilClass; def to_hash; {} end end

並做:

if env["rack.request.form_hash"].to_hash["authenticity_token"].to_s.gsub("\r\n",'')

暫無
暫無

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

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