使用 alias 为方法添加新功能

def hello # A nice simple method
  puts "Hello World" # Suppose we want to augment it...
end 
alias original_hello hello
# Give the method a backup name

def hello puts "Your attention please" original_hello puts "This has been a test" end

 应用举例:

使用alias 修改devise gem 的 current_user方法, (需求: 要返回一个 current_user的json, 但是要为这个current_user 添加一些属性 )

  alias current_user_bak current_user

  def current_user
    user = current_user_bak
    user.attributes.merge(:default_address => '中国广东')
  end

 

posted @ 2014-08-24 10:07  LaoQuans  阅读(341)  评论(0编辑  收藏  举报