今天在看calabash的wait_helpers.rb類時偶然看到了 “alias_method”。 不解,就順便查下文檔,發現幾個相關關鍵字就索性做下記錄,以便以後翻閱。
alias
alias 給已經存在的方法或全局變量設置一個別名,在重新定義已經存在的方法是,還能通過別名來調用原來的方法。alias方法的參數爲方法名或者符號名。
語法:
alias 別名 原名 #直接使用方法
alias :別名 :原名 #使用符號名
例子:
a
代碼:
class AliasDemo
$old = "old"
def hello
puts "old_hell0"
end
end
class Demo2 < AliasDemo
# 給hello方法取別名
alias old_hello hello
# 給全局變量$old取別名
alias $new_in_old $old
def hello
puts "new_hello"
end
end
obj = Demo2.new
obj.hello
obj.old_hello
puts $new_in_old
輸出結果:
new_hello
old_hell0
old
alias_method
作用和alias差不多,是Module的一個私有實例方法,只能用於給方法起別名,並且參試只能是字符串或者符號(alias 後面跟的是方法名或者全局變量)而且參數間是用“,”隔開(alias是用空格隔開)。
語法:
alias_method :new_name, :old_name
例子:
代碼:
class AliasMethodDemo
def b
puts "b"
end
alias_method :b_new, :b
b = AliasMethodDemo.new
b.b_new
b.b
end
輸出結果:
b
b
alias_method_chain
技術文檔總是會過時的,百度還能找到這個關鍵字的說明,然而已經不再使用了。
undef 和 undef_method
這兩個方法效果的等效的,都是用於取消方法定義。undef不能出現再方法主體內。undef和rails一樣,參數可以指定方法名或者符號名,undef_method後面參試只能是字符串或者符號 。如果一個類繼承了某個父類,使用了這兩個方法取消方法,會連帶父類也會一起取消。
語法:
undef 方法名 #直接使用方法名
undef :方法名 #使用符號名
undef_method :方法名
remove_method
如果你只想移除子類的方法,而不想移除父類的方法,那麼remove_method符合你需求。
語法:
remove_method :方法名
例子:
代碼:
class Parent
def hello
puts "In parent"
end
end
class Child < Parent
def hello
puts "In child"
end
end
c = Child.new
c.hello
class Child
remove_method :hello # 移除子類的hello方法,父類還在
end
c.hello
class Child
undef_method :hello # 連父類的hello方法一起刪除,不允許任何地方調用 'hello'
# undef hello # 等效上面的undef_method
end
c.hello
輸出結果:
=>:in <top (required)>': undefined method
hello’ for # (NoMethodError)
from -e:1:in load'
’
from -e:1:in
In child
In parent