Ruby元編程的一些值得注意的地方
避免無(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)文章
簡(jiǎn)單對(duì)比分析Ruby on Rails 和 Laravel
web應(yīng)用程序開發(fā)中兩個(gè)相對(duì)而言更加流行的框架是 Ruby on Rails 和 Laravel. 它們兩個(gè)都是非常成熟的項(xiàng)目,已經(jīng)面世相當(dāng)長(zhǎng)一段時(shí)間了 .2014-07-07
CentOS7下搭建ruby on rails開發(fā)環(huán)境
聽說(shuō)rails是一個(gè)比較流行的快速開發(fā)框架,對(duì)于我這個(gè)web不熟悉的人來(lái)說(shuō),那是極好的!可以快速上手,又能真正了解服務(wù)器端的各種,所以rails搞起來(lái)。不過(guò)一個(gè)完整的開發(fā)環(huán)境搭建過(guò)程完成后,真的只能用各種坑來(lái)形容~2016-02-02
Ruby on Rails實(shí)現(xiàn)最基本的用戶注冊(cè)和登錄功能的教程
這里我們主要以has_secure_password的用戶密碼驗(yàn)證功能為中心,來(lái)講解Ruby on Rails實(shí)現(xiàn)最基本的用戶注冊(cè)和登錄功能的教程,需要的朋友可以參考下2016-06-06
淘寶網(wǎng)提供的國(guó)內(nèi)RubyGems鏡像簡(jiǎn)介和使用方法
由于國(guó)內(nèi)的網(wǎng)絡(luò)環(huán)境,導(dǎo)致 rubygems.org 存放在 Amazon S3 上面的資源文件間歇性連接失敗,因此使用gem或bundle時(shí)常常會(huì)遇到長(zhǎng)久無(wú)響應(yīng)的情況2014-04-04
Windows下Ruby on Rails開發(fā)環(huán)境安裝配置圖文教程
這篇文章主要介紹了Windows下Ruby on Rails開發(fā)環(huán)境安裝配置圖文教程,ROR初學(xué)者必看,需要的朋友可以參考下2014-07-07
Ruby的面向?qū)ο蠓绞骄幊虒W(xué)習(xí)雜記
Ruby是具有面向?qū)ο筇匦缘木幊陶Z(yǔ)言,這里整理了一些Ruby的面向?qū)ο蠓绞骄幊虒W(xué)習(xí)雜記,包括類與方法等基本的面向?qū)ο笠氐闹R(shí),需要的朋友可以參考下2016-05-05

