Reputation: 267150
I have a custom class I created in my /lib folder:
/lib/user_service.rb
I also have a user_service.yml file in my /config folder.
I want to pass this yml file to my UserService class, and set some class level variables.
I'm not sure how to create class variables and how I can set these variables.
My yaml file has things like:
user_service_url: http://www.example.com/user_service/
user_service_table: "UserTable1"
So my UserService class should have these 2 attributes that are publicly accessible, and they are to be class variables (so you dont' need an instance to access it, yet instances should be able to reference it).
Can someone help me with this?
/lib/user_service.rb
module MYAPP
class UserService
end
end
Upvotes: 0
Views: 1180
Reputation: 658
You can load your yaml file into a hash for your class as follows:
module MYAPP
class UserService
SERVICES = YAML::Load(File.open(filepath))
end
end
You can then access those two variables like so:
UserService::SERVICES['user_service_url']
If you would like to access them without the hash reference style you could write methods that delve into the hash, or implement method_missing perhaps to do a hash lookup when fired.
Upvotes: 2