简体   繁体   中英

How can I refactor this Ruby and Rails code?

How can I refactor 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
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",'')

The hash indexes seem to be reused everywhere, maybe you can start there.

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

Nothing clever, but significantly shortens the line.

Something like this could work:

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

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 shorter:

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

It's DRY, concise and does not use rescue "hacks" ;-D

Rather then 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 inventory of useful NilClass methods ( to_a , to_s , to_i , etc):

class NilClass; def to_hash; {} end end

and do:

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

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