有沒有一種方法來在Ruby中修飾一個函數,因爲它是在Python中完成的?也就是說,在每個函數的開頭(和結尾?)執行一些操作。在Ruby中的函數裝飾器,如在Python中
喜歡這個:http://programmingbits.pythonblogs.com/27_programmingbits/archive/50_function_decorators.html
有沒有一種方法來在Ruby中修飾一個函數,因爲它是在Python中完成的?也就是說,在每個函數的開頭(和結尾?)執行一些操作。在Ruby中的函數裝飾器,如在Python中
喜歡這個:http://programmingbits.pythonblogs.com/27_programmingbits/archive/50_function_decorators.html
如果函數你的意思是關閉,你可以使用塊:
def foo
puts 'before code'
yield
puts 'after code'
end
foo { puts 'here is the code' }
雖然有沒有像'@ wrapper'語法? – tekknolagi
看起來像這裏有一個註釋寶石:http://rubygems.org/gems/annotation – seph
你可能會發現這篇文章和隨後的討論有趣:http://yehudakatz.com/2009/07/11/python-decorators -in-ruby/ – seph
的alias_method
工具可用於實現這樣的效果:
alias_method :old_foo, :foo
def foo
# ... before stuff ...
r = old_foo
# ... after stuff ...
return r
end
在Ruby on Rails的,您可以使用alias_method_chain
做一些爲你處理。
Python的裝飾語法(這可能不是正是你正在尋找效仿功能)可以在Ruby中通過混合來實現如Luke Redpath在「Decorator Pattern with Ruby in 8 lines」中簡潔描述的那樣修改裝飾類的方法的模塊。
我認爲一個例子會有所幫助(特別是對於我們這些不太熟悉python的人) –
啊,我的意思是函數裝飾器。對不起!我將添加一個示例 – tekknolagi