tags:

views:

34

answers:

1

If I'm building a library in ruby, what's the best way to allow users of the library to set module-wide settings that will be available to all sub classes etc of the library?

A good example would be if I'm writing a library for posting to a webservice:

TheService::File.upload("myfile.txt") # Uploads anonymously

TheService::Settings.login("myuser","mypass") # Or any other similar way of doing this
TheService::File.upload("myfile.txt") # Uploads as 'myuser'

The idea would be that unless TheService::Settings.logout is called then all TheService operations would be conducted under myuser's account.

Any ideas?

A: 

store the data in class variables (or static varibales). You can do something like this:

module TheService
  class Settings
    def self.login(username,password)
      @@username = username
      @@password = password
    end
    def username
      @@username
    end
    def password
      @@password
    end
    def self.logout
      @@username = @@password = nil
    end
  end
end

Now you can access these setting from Everywhere via TheService::Settings.username or TheService::Settings.password

jigfox
Spot on, don't know why i didn't think of this! Cheers!
JP