user3063045 user3063045 - 1 month ago 7
Ruby Question

Ruby Access Class Variables Easily

I've created a class that I'm using to store configuration data. Currently the class looks like this:

class Configed
@@username = "test@gmail.com"
@@password = "password"
@@startpage = "http://www.example.com/login"
@@nextpage = "http://www.example.com/product"
@@loginfield = "username"
@@passwordfield = "password"
@@parser = "button"
@@testpage = "http://www.example.com/product/1"
@@button1 = "button1"
def self.username
@@username
end
def self.password
@@password
end
def self.startpage
@@startpage
end
def self.nextpage
@@nextpage
end
def self.loginfield
@@loginfield
end
def self.passwordfield
@@passwordfield
end
def self.parser
@@parser
end
def self.testpage
@@testpage
end
def self.button1
@@button1
end
end


To access the variables I'm using:

# Config file
require_relative 'Configed'

# Parse config
startpage = Configed.startpage
loginfield = Configed.loginfield
passwordfield = Configed.passwordfield
username = Configed.username
password = Configed.password
nextpage = Configed.nextpage
parser = Configed.parser
testpage = Configed.testpage


This is not very modular. Adding additional configuration data needs to be referenced in three places.

Is there a better way of accomplishing this?

Answer

You can make class level instance variables...

class Configed
  @username = "test@gmail.com"
  @password = "password"
  @startpage = "http://www.example.com/login"
  # ...
  class << self
    attr_accessor :username, :password, :startpage # ...
  end
end

It's somewhat more compact, and still gives you

username = Configed.username
# ...