Class: Pokan::Cluster::Configuration
- Inherits:
-
Yagni::Hash
- Object
- Yagni::Hash
- Pokan::Cluster::Configuration
- Defined in:
- lib/pokan-cluster/configuration.rb
Overview
Class used to hold configuration options for anything. It inherits from Yell::Hash, so that the options are can be passed in a usual Ruby hash. Optionally, you can pass it a string containing your data and an object which responds to the method parse
, which will take the data string and build the corresponding hash.
The options passed can be accessed later via the get
method, used in the example above (see further details in Pokan::Cluster::Configuration#get)
Usage
# If we wanted to use a YAML configuration file...
# and our file was the following:
# pokan:
# cluster: "configuration"
class YAMLParser
def self.parse(data)
YAML.load(data)
end
end
c = Pokan::Cluster::Configuration.new(File.read('config.yaml'), YAMLParser)
c.get('pokan.cluster') #=> "configuration"
Instance Method Summary collapse
-
#get(query) ⇒ Object
Main method, used to query values from your configuration.
-
#initialize(data, parser = nil) ⇒ Configuration
constructor
Creates a new Pokan::Cluster::Configuration object, containing the data passed.
-
#load_data(data, parser) ⇒ Object
Loads the data in case a string was passed in the initialization.
Constructor Details
#initialize(data, parser = nil) ⇒ Configuration
Creates a new Pokan::Cluster::Configuration object, containing the data passed. It can be either a usual Ruby hash or a String with your data, as long as you provide a parser which responds to the method parse
taking the string as parameter and returning the corresponding hash.
37 38 39 40 41 42 43 44 45 46 |
# File 'lib/pokan-cluster/configuration.rb', line 37 def initialize(data, parser=nil) case data when Object::Hash @data = data when String @data = load_data(data, parser) end super(@data) end |
Instance Method Details
#get(query) ⇒ Object
Main method, used to query values from your configuration. It accepts as a parameter a string containing the “path” to reach the data you want.
h = { :max_connections => "10", :proto => { :tcp => true } }
c = Pokan::Cluster::Configuration.new(h)
c.get('max_connections') #=> "10"
c.get('proto.tcp') #=> "true"
62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/pokan-cluster/configuration.rb', line 62 def get(query) step = nil # contains consequent results of our query path = query.split '.' path.each { |param| step = send(param.to_sym) } step rescue NoMethodError nil ensure reload end |
#load_data(data, parser) ⇒ Object
Loads the data in case a string was passed in the initialization. It actually just calls the method parse
on the parser object
50 51 52 |
# File 'lib/pokan-cluster/configuration.rb', line 50 def load_data(data, parser) parser.parse(data) end |