Skip to content
This repository has been archived by the owner on Mar 22, 2021. It is now read-only.

NameError: `@_current_account/user' is not allowed as an instance variable name #182

Open
mattlemx opened this issue Aug 12, 2017 · 2 comments

Comments

@mattlemx
Copy link

mattlemx commented Aug 12, 2017

Hi!
#<NameError: `@_current_account/user' is not allowed as an instance variable name>

Ruby 2.3.3
Rails 5.1.3 (API mode)
knock 2.1.1

I appreciate all of your work on this gem. I ran into an issue when I namespaced my User model. It looks like when authenticate_for is called with a namespaced entity class (e.g. Account::User) it uses underscore to set the getter_name to current_account_user, but when the underscore method is called on the string it turns the :: into a / to convert namespaces to paths. (http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-underscore)

The error is then thrown when the define_current_entity_getter method tries to create an instance variable with the value of getter_name, @_current_account/user.

application_controller.rb

include Knock::Authenticable
  # include Pundit
  before_action :authenticate_account_user

  private

  # Override Authenticate_for because it trys to create a variable
  # using the class name, but underscore creates a path which includes
  # invalid characters
  def authenticate_for(entity_class)
    getter_name = "current_#{entity_class.to_s.gsub(/::/, '').underscore}"
    define_current_entity_getter(entity_class, getter_name)
    public_send(getter_name)
  end

  def authenticate_account_user
    authenticate_for Account::User
  end

account/user.rb

module Account
  class User < ApplicationRecord
    self.table_name_prefix = 'account_'.freeze

    has_secure_password
  end
end

Current work around:
To fix this, I overrode the authenticate_for method in my ApplicationController adding gsub before underscore to strip out the :: and everything works fine.

def authenticate_for(entity_class)
    getter_name = "current_#{entity_class.to_s.gsub(/::/, '').underscore}"
    define_current_entity_getter(entity_class, getter_name)
    public_send(getter_name)
end

^^ This didn't work, it no longer authenticated the user. Every request with and without JWT worked.

@ethier
Copy link

ethier commented Dec 15, 2017

@matthewl20 FYI, this is addressed in master:

def authenticate_for entity_class
  getter_name = "current_#{entity_class.to_s.parameterize.underscore}"
  define_current_entity_getter(entity_class, getter_name)
  public_send(getter_name)
end

@mattlemx
Copy link
Author

mattlemx commented Dec 15, 2017 via email

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants