"未定义的方法'成为'为零:NilClass"它不应该

时间:2017-05-04 14:18:38

标签: ruby ruby-on-rails-4 devise

我今天正在测试一个片段

unless resource.nil?
  resource = resource.becomes(Accounts::Admin)
end

这会引发错误

  

未定义的方法`成为'为零:NilClass

如果我这样做

unless resource.nil?
  a = resource.becomes(Accounts::Admin)
  resource = a
end

一切顺利。

如果首先执行=运算符的右边部分,有什么区别?

编辑:

发生了令人讨厌的事情,if false下的最后一行正在执行,但是" ALOHA"从未打印过。

<%
puts "AAAA #{resource.inspect}"
if false
    puts "ALOHA"

    # this line is being executed !
    # if I comment it out the BBBB output is correct
    resource = nil
end 
puts "BBBB #{resource.inspect}"
%>

打印

  

AAAA用户ID:nil,nome:nil,endereco_id:nil,created_at:nil,   updated_at:nil,email:&#34;&#34;

     

BBBB无

但如果我这样做

<%
res = resource

puts "AAAA #{res.inspect}"
if false
  puts "ALOHA"
  res = nil
end 
puts "BBBB #{res.inspect}"
%>

正确打印

  

AAAA用户ID:nil,nome:nil,endereco_id:nil,created_at:nil,   updated_at:nil,email:&#34;&#34;

     

BBBB用户名:nil,nome:nil,   endereco_id:nil,created_at:nil,updated_at:nil,email:&#34;&#34;

我已经尝试重启服务器了。此代码段位于devise/registrations/new.html.erbresource变量应该是User的一个实例,由设计的RegistrationController创建

我已经检查了隐藏字符的文本,我粘贴的片段是正在测试的文件的全文。

这是~/.rvm/gems/ruby-2.3.3@mygem/gems/devise-4.2.0/app/controllers/devise/registrations_controller.rb

处控制器的内容
class Devise::RegistrationsController < DeviseController
  prepend_before_action :require_no_authentication, only: [:new, :create, :cancel]
  prepend_before_action :authenticate_scope!, only: [:edit, :update, :destroy]
  prepend_before_action :set_minimum_password_length, only: [:new, :edit]

  # GET /resource/sign_up
  def new
    build_resource({})
    yield resource if block_given?
    respond_with resource
  end

  # POST /resource
  def create
    build_resource(sign_up_params)

    resource.save
    yield resource if block_given?
    if resource.persisted?
      if resource.active_for_authentication?
        set_flash_message! :notice, :signed_up
        sign_up(resource_name, resource)
        respond_with resource, location: after_sign_up_path_for(resource)
      else
        set_flash_message! :notice, :"signed_up_but_#{resource.inactive_message}"
        expire_data_after_sign_in!
        respond_with resource, location: after_inactive_sign_up_path_for(resource)
      end
    else
      clean_up_passwords resource
      set_minimum_password_length
      respond_with resource
    end
  end

  # GET /resource/edit
  def edit
    render :edit
  end

  # PUT /resource
  # We need to use a copy of the resource because we don't want to change
  # the current user in place.
  def update
    self.resource = resource_class.to_adapter.get!(send(:"current_#{resource_name}").to_key)
    prev_unconfirmed_email = resource.unconfirmed_email if resource.respond_to?(:unconfirmed_email)

    resource_updated = update_resource(resource, account_update_params)
    yield resource if block_given?
    if resource_updated
      if is_flashing_format?
        flash_key = update_needs_confirmation?(resource, prev_unconfirmed_email) ?
          :update_needs_confirmation : :updated
        set_flash_message :notice, flash_key
      end
      bypass_sign_in resource, scope: resource_name
      respond_with resource, location: after_update_path_for(resource)
    else
      clean_up_passwords resource
      respond_with resource
    end
  end

  # DELETE /resource
  def destroy
    resource.destroy
    Devise.sign_out_all_scopes ? sign_out : sign_out(resource_name)
    set_flash_message! :notice, :destroyed
    yield resource if block_given?
    respond_with_navigational(resource){ redirect_to after_sign_out_path_for(resource_name) }
  end

  # GET /resource/cancel
  # Forces the session data which is usually expired after sign
  # in to be expired now. This is useful if the user wants to
  # cancel oauth signing in/up in the middle of the process,
  # removing all OAuth session data.
  def cancel
    expire_data_after_sign_in!
    redirect_to new_registration_path(resource_name)
  end

  protected

  def update_needs_confirmation?(resource, previous)
    resource.respond_to?(:pending_reconfirmation?) &&
      resource.pending_reconfirmation? &&
      previous != resource.unconfirmed_email
  end

  # By default we want to require a password checks on update.
  # You can overwrite this method in your own RegistrationsController.
  def update_resource(resource, params)
    resource.update_with_password(params)
  end

  # Build a devise resource passing in the session. Useful to move
  # temporary session data to the newly created user.
  def build_resource(hash=nil)
    self.resource = resource_class.new_with_session(hash || {}, session)
  end

  # Signs in a user on sign up. You can overwrite this method in your own
  # RegistrationsController.
  def sign_up(resource_name, resource)
    sign_in(resource_name, resource)
  end

  # The path used after sign up. You need to overwrite this method
  # in your own RegistrationsController.
  def after_sign_up_path_for(resource)
    after_sign_in_path_for(resource)
  end

  # The path used after sign up for inactive accounts. You need to overwrite
  # this method in your own RegistrationsController.
  def after_inactive_sign_up_path_for(resource)
    scope = Devise::Mapping.find_scope!(resource)
    router_name = Devise.mappings[scope].router_name
    context = router_name ? send(router_name) : self
    context.respond_to?(:root_path) ? context.root_path : "/"
  end

  # The default url to be used after updating a resource. You need to overwrite
  # this method in your own RegistrationsController.
  def after_update_path_for(resource)
    signed_in_root_path(resource)
  end

  # Authenticates the current scope and gets the current resource from the session.
  def authenticate_scope!
    send(:"authenticate_#{resource_name}!", force: true)
    self.resource = send(:"current_#{resource_name}")
  end

  def sign_up_params
    devise_parameter_sanitizer.sanitize(:sign_up)
  end

  def account_update_params
    devise_parameter_sanitizer.sanitize(:account_update)
  end

  def translation_scope
    'devise.registrations'
  end
end

红宝石2.3.3 铁轨(4.2.7.1) 设计(4.2.0)

3 个答案:

答案 0 :(得分:5)

看看这个红宝石片段:

if true
  foo = "hello"
end
puts foo

#=> hello

这一个:

if false
  foo = "hello"
end
puts foo

#=> nil

在许多语言中,if语句都有自己的范围,但在ruby中它们共享周围函数的范围。这意味着在if语句中声明的变量可以在if语句之外访问。

这里的问题是变量是在编译时声明的,之后ruby知道if语句是true还是false。所以在ruby中,所有局部变量都被声明并初始化为nil,即使它们在条件语句中也是如此。

此代码:

unless resource.nil?
  resource = resource.becomes(Accounts::Admin)
end

由于ruby中的另一个规则导致局部变量优先于方法而导致问题。因此,当您说resource = resource时,您实际上正在调用方法resource并将其值保存到局部变量resource,然后将该方法用相同的名称覆盖。

最终你得到了错误:

  

未定义的方法`成为&#39;为零:NilClass

因为在编译时,正在创建局部变量resource,使方法蒙上阴影。然后,在运行时,正在执行条件,因为resource尚未nil。但是在您创建局部变量的行中,它会立即进入范围,使resource = nil并导致错误。

错误可以在这个通用示例中重现:

def blah
  "foo"
end

unless blah.nil?
  blah = blah.size
end
puts blah

它的修复方法是指定方法本身:

def blah
  "foo"
end

def blah= value
  #do nothing
end

unless blah.nil?
  self.blah = blah.size
end

puts blah

话虽如此,我不确定设计是否实际实现resource=()。如果它没有,那么你最好的解决方案是你已经提出的 - 使用局部变量:

unless resource.nil?
  res = resource.becomes(Accounts::Admin)
end
puts res

在做了一些研究之后,我发现ruby中的局部变量是根据文件中的位置从上到下和从左到右定义的,而不是它们在程序流中的位置。例如:

if x="foo"
  puts x
end
#=> "foo"

puts y if y="foo"
#NameError: undefined variable or method 'y'

这是红宝石规范according to matz的一部分。

答案 1 :(得分:0)

在IRb中试试这个,应该没问题:

a = 'hello'
unless a.nil?
  a = a.upcase
end
a
# => "HELLO"

第二个例子相当于第一个例子,=右侧的表达式被分配给左边的var。

也许有些隐藏的字符或拼写错误? 你确定stacktrace指向那一行,你在文件的其他地方使用becomes吗?

答案 2 :(得分:0)

如果使用ruby Ruby 2.3.0及更高版本,请使用安全导航操作符(&。)

resource = resource&.becomes(Accounts::Admin)