gpt4 book ai didi

ruby-on-rails - 使用设计上下文的 "super"和 "super do |u|"之间的区别

转载 作者:数据小太阳 更新时间:2023-10-29 06:43:49 25 4
gpt4 key购买 nike

好吧,我想我得到了什么 super 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

最佳答案

让我试着解释一下这里发生了什么:

class Users::RegistrationsController < Devise::RegistrationsController
def new
super do |user|
user.charge_and_save_customer
puts user.inspect
end
end
end

当您调用 super 时,您将返回到父 new 操作,因此现在将执行以下代码:

def new
build_resource({})
set_minimum_password_length
yield resource if block_given?
respond_with self.resource
end

但是等等...这里有一个yield,所以它将当前的resource yield给block,你可以把block想象成一个方法,它需要一个参数 (user),这里的 resource (from parent) 将是参数:

# Here resource is assigned to user
user.charge_and_save_customer
puts user.inspect

现在,由于 block 已完全执行,它将再次开始执行 super :

respond_with self.resource

关于ruby-on-rails - 使用设计上下文的 "super"和 "super do |u|"之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30426894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com