开发者

How can I refactor this Ruby and Rails code?

开发者 https://www.devze.com 2023-02-11 22:23 出处:网络
How can I refactor this code? if env[\"rack.request.form_hash\"] && env[\"rack.request.form_hash\"][\"authenticity_token\"]

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开发者_StackOverflow"].gsub("\r\n",'')
end


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


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

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",'')
0

精彩评论

暂无评论...
验证码 换一张
取 消