我怎样才能重构这个Ruby和Rails代码?

时间:2011-02-17 15:16:33

标签: ruby-on-rails ruby

如何重构此代码?

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

5 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:1)

如果你有andand宝石,你可以跳过检查并直接进入:

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

答案 2 :(得分:0)

哈希索引似乎在任何地方都可以重用,也许你可以从那里开始。

   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)

答案 3 :(得分:0)

我建议:

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

答案 4 :(得分:0)

而不是使用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",'')