Ruby: Allowing a module to have settings
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 wi开发者_如何学Goll 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?
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
精彩评论