最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2015年08月03日 16:35:02   投稿:goldensun  
這篇文章主要介紹了Ruby元編程的一些值得注意的地方,作者自己用實(shí)際代碼給出了相關(guān)示例,需要的朋友可以參考下

  避免無(wú)限循環(huán)的元編程。

    寫一個(gè)函數(shù)庫(kù)時(shí)不要使核心類混亂(不要使用 monkey patch)。

    代碼塊形式最好用于字符串插值形式。
        當(dāng)你使用字符串插值形式,總是提供 __FILE__ 和 __LINE__,使得你的回溯有意義。

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

        define_method 最好用 class_eval{ def ... }

    當(dāng)使用 class_eval (或者其他的 eval)以及字符串插值,添加一個(gè)注釋塊使之在插入的時(shí)候顯示(這是我從 rails 代碼學(xué)來(lái)的實(shí)踐):

 # 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,它使得回溯變得很麻煩,這個(gè)習(xí)慣不被列在 #methods,拼寫錯(cuò)誤的方法可能也在默默的工作,例如 nukes.launch_state = false。考慮使用委托,代理或者是 define_method ,如果必須這樣,使用 method_missing ,
        確保 也定義了 respond_to_missing?
        僅捕捉字首定義良好的方法,像是 find_by_* ― 讓你的代碼越肯定(assertive)越好。
        在語(yǔ)句的最后調(diào)用 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


相關(guān)文章

最新評(píng)論

富宁县| 馆陶县| 商城县| 宁武县| 阳曲县| 榆树市| 金寨县| 梨树县| 保亭| 西乌珠穆沁旗| 缙云县| 灵武市| 四子王旗| 古丈县| 内乡县| 石家庄市| 堆龙德庆县| 青川县| 旌德县| 日土县| 奉新县| 连平县| 昌黎县| 石狮市| 庆云县| 广饶县| 永嘉县| 五河县| 分宜县| 疏附县| 博客| 剑河县| 西昌市| 繁昌县| 岳池县| 炎陵县| 七台河市| 连云港市| 新宁县| 鸡西市| 衡山县|