Kleber S.
Kleber S.

Reputation: 8240

How to access YAML sublevel item in a nested variable?

Getting the error:

You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]

APP_CONFIG are loading fine.

account_type = 'sample'
allowed = APP_CONFIG['account']["#{account_type}"]['highlight']

Error points to 'allowed' variable line.

The method that I currently trying to is:

  def self.allow_highlight?(account)
    account_type = Account.find(account).active_pack # returning a string - OK
    logger.debug account_type.class # checked on console - OK
    allowed = APP_CONFIG['account']["#{account_type}"]['highlight'] # Error line
    if total_account_highlight > allowed
        false
    else
        true
    end
  end

Hope you understand. Any doubts, please ask me.

Thanks!

Upvotes: 0

Views: 683

Answers (2)

Rabbott
Rabbott

Reputation: 4332

I would first make sure that APP_CONFIG is being set in an initializer.

Secondly, this error will arise if APP_CONFIG, or account_type are nil, are you actually setting account_type right before that line like in your code, or is it being supplied from somewhere and actually does not contain a value? If account_type is nil, empty, or contains a value that is not supplied in your YAML file, it will throw an error. So, you should verify the contents of those two variables.

ALSO, if you just made APP_CONFIG in your initializers, make sure you restart Rails, as it only gets updated on initialization of the server

Upvotes: 1

tjeden
tjeden

Reputation: 2079

account_type should be string:

 allowed = APP_CONFIG['account']["#{account_type.to_s}"]['highlight']

or

 allowed = APP_CONFIG['account']["#{account_type.class}"]['highlight']

Upvotes: 1

Related Questions