Ruby元編程的一些值得注意的地方_ruby專題

來源:互聯網
上載者:User

  避免無限迴圈的元編程。

    寫一個函數庫時不要使核心類混亂(不要使用 monkey patch)。

    代碼塊形式最好用於字串插值形式。
        當你使用字串插值形式,總是提供 __FILE__ 和 __LINE__,使得你的回溯有意義。

 class_eval 'def use_relative_model_naming?; true; end', __FILE__, __LINE__

        define_method 最好用 class_eval{ def ... }

    當使用 class_eval (或者其他的 eval)以及字串插值,添加一個註解區塊使之在插入的時候顯示(這是我從 rails 代碼學來的實踐):

 # from activesupport/lib/active_support/core_ext/string/output_safety.rb UNSAFE_STRING_METHODS.each do |unsafe_method|  if 'String'.respond_to?(unsafe_method)  class_eval <<-EOT, __FILE__, __LINE__ + 1   def #{unsafe_method}(*args, &block)  # def capitalize(*args, &block)   to_str.#{unsafe_method}(*args, &block) # to_str.capitalize(*args, &block)   end          # end   def #{unsafe_method}!(*args)    # def capitalize!(*args)   @dirty = true       # @dirty = true   super         # super   end          # end  EOT  end end

    避免在元編程中使用 method_missing,它使得回溯變得很麻煩,這個習慣不被列在 #methods,拼字錯誤的方法可能也在默默的工作,例如 nukes.launch_state = false。考慮使用委託,代理或者是 define_method ,如果必須這樣,使用 method_missing ,
        確保 也定義了 respond_to_missing?
        僅捕捉字首定義良好的方法,像是 find_by_* ― 讓你的代碼越肯定(assertive)越好。
        在語句的最後調用 super
        delegate 到確定的、非魔法方法中:

 # bad def method_missing?(meth, *args, &block)  if /^find_by_(?<prop>.*)/ =~ meth  # ... lots of code to do a find_by  else  super  end end # good def method_missing?(meth, *args, &block)  if /^find_by_(?<prop>.*)/ =~ meth  find_by(prop, *args, &block)  else  super  end end # best of all, though, would to define_method as each findable attribute is declared


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.