【发布时间】:2015-08-06 06:12:47
【问题描述】:
好的,所以我想我得到了超级 does 独立。基本上在设计中,如果Users::RegistrationsController < Devise::RegistrationsController,那么在任何操作上,拥有super 将首先调用父Devise::RegistrationsController 中相同命名操作的逻辑,然后再调用您编写的内容。
换句话说……
class Devise::RegistrationsController
def new
puts "this is in the parent controller"
end
end
class Users::RegistrationsController < Devise::RegistrationsController
def new
super
puts "this is in the child controller"
end
end
# Output if users#new is run would be:
# => "this is in the parent controller"
# => "this is in the child controller"
# If super were reversed, and the code looked like this
# class Users::RegistrationsController < Devise::RegistrationsController
# def new
# puts "this is in the child controller"
# super
# end
# end
# Then output if users#new is run would be:
# => "this is in the child controller"
# => "this is in the parent controller"
我很好奇的是我见过一些人这样做:
class Users::RegistrationsController < Devise::RegistrationsController
def new
super do |user|
puts "something"
end
end
end
我很难理解do block 正在完成的工作。就我而言,在创建资源(用户)之后,我想对该资源(用户)调用一个附加方法。
当前代码:
class Users::RegistrationsController < Devise::RegistrationsController
def new
super do |user|
user.charge_and_save_customer
puts user.inspect
end
end
end
我只是想知道这与做有什么不同:
class Users::RegistrationsController < Devise::RegistrationsController
def new
super
resource.charge_and_save_customer
puts resource.inspect
end
end
如果有帮助,我在下面包含了父 Devise::RegistrationsController 代码:
def new
build_resource({})
set_minimum_password_length
yield resource if block_given?
respond_with self.resource
end
【问题讨论】:
-
他们的
new方法需要一个块(因此yield)
标签: ruby-on-rails ruby ruby-on-rails-4 devise super