-1
class User 
  class << self
    attr_reader :passwordManagerAccountID
    attr_reader :masterPassword

    def session(passwordManagerAccountID , masterPassword)
      @@passwordManagerAccountID = passwordManagerAccountID
      @@masterPassword = masterPassword
    end
  end  
end

User.session("sdsd" , "sdsd")
User.passwordManagerAccountID #=> no output
User.masterPassword #=> no output

I am trying to use attr_reader on class variable but it doesn't seem to work.

I google searched but I don't seem to understand. So, if someone can explain me in simple terms the problem and its solution (without using getter and setter methods).

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
  • This may have also been answered here: http://stackoverflow.com/questions/4370960/what-is-attr-accessor-in-ruby Did you really google search for this beforehand?? – Kevin Brown Feb 17 '14 at 20:22

2 Answers2

1

attr_reader just creates a method like this:

def masterPassword
  @masterPassword
end

So you either must access the correct class instance variable in session (e.g. @masterPassword) or forego using attr_reader and write your own accessor:

def masterPassword
  @@masterPassword
end

Unless you happen to have ActiveSupport which does provide cattr_accessor, cattr_reader, & cattr_writer.

See also Why should @@class_variables be avoided in Ruby? for why you perhaps should just use class instance variables instead.

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
0

attr_reader is not reading class variables, but instance variables - you need to use class instance variables:

def session(passwordManagerAccountID , masterPassword)
  @passwordManagerAccountID = passwordManagerAccountID
  @masterPassword = masterPassword
end

Please mind the Ruby naming convention: it should be password_manager_accound_id and similar. There's no lowerCamelCase in Ruby.

BroiSatse
  • 44,031
  • 8
  • 61
  • 86