jam*_*mes 12 ruby ruby-on-rails super devise ruby-on-rails-4
好的,所以我觉得我得到了超级does独立的东西.基本上在Devise中,if 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"
Run Code Online (Sandbox Code Playgroud)
我很好奇的是,我看到有些人这样做:
class Users::RegistrationsController < Devise::RegistrationsController
def new
super do |user|
puts "something"
end
end
end
Run Code Online (Sandbox Code Playgroud)
我很难绕过do block正在完成的事情.在我的例子中,在创建资源(用户)之后,我想在该资源(用户)上调用另一个方法.
当前代码:
class Users::RegistrationsController < Devise::RegistrationsController
def new
super do |user|
user.charge_and_save_customer
puts user.inspect
end
end
end
Run Code Online (Sandbox Code Playgroud)
我只是想知道这与做的有什么不同:
class Users::RegistrationsController < Devise::RegistrationsController
def new
super
resource.charge_and_save_customer
puts resource.inspect
end
end
Run Code Online (Sandbox Code Playgroud)
如果它有用,我已经包含Devise::RegistrationsController下面的父代码:
def new
build_resource({})
set_minimum_password_length
yield resource if block_given?
respond_with self.resource
end
Run Code Online (Sandbox Code Playgroud)
Sha*_*med 16
让我试着解释一下这里发生了什么:
class Users::RegistrationsController < Devise::RegistrationsController
def new
super do |user|
user.charge_and_save_customer
puts user.inspect
end
end
end
Run Code Online (Sandbox Code Playgroud)
当您正在呼叫时super,您将返回到父new操作,因此以下代码将立即执行:
def new
build_resource({})
set_minimum_password_length
yield resource if block_given?
respond_with self.resource
end
Run Code Online (Sandbox Code Playgroud)
但是等等......这里是一个yield,所以它产生了当前resource的块,你可以认为块像一个方法,它需要一个参数(user),这里resource(来自父)将是参数:
# Here resource is assigned to user
user.charge_and_save_customer
puts user.inspect
Run Code Online (Sandbox Code Playgroud)
现在,由于块完全执行,它将再次开始执行super:
respond_with self.resource
Run Code Online (Sandbox Code Playgroud)