How can I reorganize this Ruby and Rails code?

How can I reorganize this 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 
+4
source share
5 answers
 env["rack.request.form_hash"]["authenticity_token"] = env["rack.request.form_hash"]["authenticity_token"].gsub("\r\n",'') rescue nil 

or with in-place editing

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

if you have andand gem, you can skip the check and go straight to:

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

Hash indexes seem to be used everywhere, maybe you can start there.

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

Nothing smart, but significantly shortens the line.

Something like this might work:

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

I would recommend:

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

or similar but short:

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

It is DRY, concise and does not use rescue β€œhacks”; -D

0
source

Instead of using andand or try , I would do:

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

or add to_hash to the list of useful NilClass methods ( to_a , to_s , to_i , etc.):

 class NilClass; def to_hash; {} end end 

and execute:

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

Source: https://habr.com/ru/post/1340187/


All Articles