Nishan Hitang
Nishan Hitang

Reputation: 805

Undefined method `[]' for nil:NilClass for Warden

I have a Helper module as follows. The module uses warden.

module V0
  module Api
    # @private
    module Helpers
      def warden
        env['warden']
      end

      # Used to require an authenticated user for a particular action.
      def protected!
        warden.authenticate!
      end

      def current_user
        warden.user
      end

      def parse_json_body
        request.body.rewind
        request_body = current_user ? current_user.keychain_replace(request.body.read) : request.body.read
        @parsed_body = JSON.parse(request_body, symbolize_names: true)
        params.update @parsed_body
      end
    end
  end
end

The module parses a request. In the line

request_body = current_user ? current_user.keychain_replace(request.body.read) : request.body.read

I tried to check if current user is set and get request_body accordingly. However I get the following errors.

NoMethodError:
       undefined method `[]' for nil:NilClass
     # (eval):2:in `method_missing'
     # ./app/api/v0/helpers.rb:11:in `warden'
     # ./app/api/v0/helpers.rb:23:in `current_user'
     # ./app/api/v0/helpers.rb:37:in `parse_json_body'

If no current user is set then it should have set

request_body = request.body.read

but I don't get this

Upvotes: 1

Views: 459

Answers (2)

Stobbej
Stobbej

Reputation: 1090

The problem seems to lie in your warden method. The env variable is nil there. Check if your module is loaded in correctly.

Upvotes: 0

Tim
Tim

Reputation: 1005

Instead of

request_body = current_user ? current_user.key ..

try

request_body = !current_user.nil? ? current_user.key ..

That would get a true/false response to evaluate.. I put the ! in to preserve the order of your arguments.

This is a bit of a guess, but I think it's evaluating a nil, rather than looking for false properties..

Upvotes: 1

Related Questions