【问题标题】:Difference between "super" and "super do |u|" using context of Devise“super”和“super do |u|”的区别使用设计的上下文
【发布时间】: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


【解决方案1】:

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

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 生成给块,你可以把块想象成一个方法,它需要一个参数(user),这里是@ 987654328@(来自父级)将是参数:

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

现在,由于该块已完全执行,它将再次开始执行超级:

respond_with self.resource

【讨论】:

  • 我明白了,所以在这种情况下,由于块中有一个super 和一个yield,那么基本上super do 中的代码在调用yield 的任何地方都会执行。在这种情况下,它允许我在父操作中间注入代码。如果没有yield 语句,那么super do 将毫无用处,而super 本身将运行整个父操作(这意味着我可以在开头或结尾注入代码)。对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 2017-05-23
  • 2021-08-09
  • 2019-06-07
  • 1970-01-01
相关资源
最近更新 更多