2017-05-04 4 views
4

私はこの「未定義のメソッドは、ゼロのため 『になる』:NilClass」それはすべきではない

をすれば、これはエラー

undefined method `becomes' for nil:NilClass

を提起

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

今日スニペットをテストしていました

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

すべてが正しく機能します。

=演算子の右部分が最初に実行される場合の相違点は何ですか?

EDIT:

厄介な何かが起こっている、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 User id: nil, nome: nil, endereco_id: nil, created_at: nil, updated_at: nil, email: ""

BBBB nil

を出力しますが、私はこの

<% 
res = resource 

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

をすれば、それは正しく

AAAA User id: nil, nome: nil, endereco_id: nil, created_at: nil, updated_at: nil, email: ""

BBBB User id: nil, nome: nil, endereco_id: nil, created_at: nil, updated_at: nil, email: ""

を印刷する私はすでに、サーバーを再起動しようとしています。このスニペットはdevise/registrations/new.html.erbです。 resource変数は、Userのインスタンスであり、deviseのRegistrationControllerによって作成されたものです。

隠し文字のテキストをチェックしました。ここに貼り付けたスニペットは、テストするファイルの全文です。

この

~/.rvm/gems/[email protected]/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)

+0

'resource'は、deviseコントローラのメソッドです。状況を説明するならば、' resource'は優先度を持ち、メソッドをシャドウする変数を作成すると 'resource'がメソッドを呼び出します。変数の代わりにメソッドを使用するには 'self.resource'を行う必要があります。 – Kris

答えて

5

このルビーの抜粋を見てみましょう。

if true 
    foo = "hello" 
end 
puts foo 

#=> hello 

そして、この1:多くの言語で

if false 
    foo = "hello" 
end 
puts foo 

#=> nil 

、-文があれば、独自のスコープを持っていますが、Rubyで、彼らは周囲の範囲を共有します関数。これはif文の中で宣言された変数がif文の外部からアクセス可能であることを意味します。

ここでの問題は、rubyがif-statementがtruefalseかどうかを知る前に、変数がコンパイル時に宣言されることです。したがって、ルビでは、すべてのローカル変数は宣言され、条件文に入っていてもnilとして初期化されます。

このコード:

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

が原因の方法より、ローカル変数に優先権を与えるルビーで別のルールの問題を引き起こします。したがって、resource = resourceと言うときは、実際にはメソッドresourceを呼び出してその値をローカル変数resourceに保存します。この場合、ローカル変数は同じ名前でメソッドをオーバーシュートします。コンパイル時に、ローカル変数resourceメソッドをovershadowing、作成されているので、

undefined method `becomes' for nil:NilClass

最終的に、あなたはエラーを取得しています。その後、実行時に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=()を実装しています。そうでない場合は、あなたの最善の解決策は、あなたがすでにローカル変数を使用with-思い付いたものです:いくつかの研究を行った後

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

が、私はルビー内のローカル変数は、トップから定義されていることがわかりましたプログラムフロー内での位置ではなく、ファイル内の位置に基づいて、左から右に移動します。例:

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

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

これはルビー仕様の一部です(according to matz)。

+1

これは正しいです。あなたは 'self.resource ='を試すことができます。 – Kris

0

IRBでこれを試してみてください、それが必要大丈夫:

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

第二の例では、第一に相当する、=の右側に発現左のvarに代入されます。

多少の隠れた文字や間違ったスペルですか? stacktraceがその行を指していますか?becomesをファイルの別の場所に使用していますか?

+0

はい、私は確信しています。本当に厄介なもののように見えますが、まだ解明しようとしています。隠された文字を確認します。ありがとうございます。 – Gus

+0

@kris 'a'がメソッドとして起動すると失敗します –

+0

@SergioTulentsev"メソッドとして開始する "とは何を意味するのか不明です。 "何か";あなたは 'a = 'hello''をすることができません。 – Kris

関連する問題