Class: Tablets::Utils::Config
- Inherits:
-
Object
- Object
- Tablets::Utils::Config
- Defined in:
- lib/tablets/utils/config.rb
Overview
Config utility. Allows to write configs in declarative form. And fetch values with defaults:
config = Config.new do
some_var 32
another_var 42
some_callback do |arg|
do_something_with arg
end
end
config.get(:some_var) #=> 32
config.get(:non_existent_var) #=> ArgumentError
config.get(:non_existent_var, 'default') #=> 'default'
config.call(:some_callback, 'my_arg') { |arg| default_action arg }
Instance Method Summary collapse
-
#apply(&block) ⇒ Object
Executes block in config context.
-
#call(name, *params, &default) ⇒ Object
Calls callback If no calbback defined, calls default If no default raises ArgumentError.
-
#get(name, default = nil, &default_block) ⇒ Object
Returns value If no value defined, returns default If no default raises ArgumentError.
-
#has?(name) ⇒ Boolean
Checks if value or callback is defined with specified name.
-
#initialize(&block) ⇒ Config
constructor
Initializes config with block Block is optional and can be applied later.
Constructor Details
#initialize(&block) ⇒ Config
Initializes config with block Block is optional and can be applied later
26 27 28 29 30 |
# File 'lib/tablets/utils/config.rb', line 26 def initialize(&block) @hash = {} apply(&block) unless block.nil? end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args, &block) ⇒ Object (private)
Gathers all calls
77 78 79 |
# File 'lib/tablets/utils/config.rb', line 77 def method_missing(name, *args, &block) @hash[name] = [*args, block] end |
Instance Method Details
#apply(&block) ⇒ Object
Executes block in config context
33 34 35 |
# File 'lib/tablets/utils/config.rb', line 33 def apply(&block) instance_eval(&block) end |
#call(name, *params, &default) ⇒ Object
Calls callback If no calbback defined, calls default If no default raises ArgumentError
62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/tablets/utils/config.rb', line 62 def call(name, *params, &default) callback = @hash[name][0] if @hash[name] if !callback.nil? callback.call(*params) elsif !default.nil? default.call(*params) else fail ArgumentError, "Callback :#{name} is not registered." end end |
#get(name, default = nil, &default_block) ⇒ Object
Returns value If no value defined, returns default If no default raises ArgumentError
45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/tablets/utils/config.rb', line 45 def get(name, default = nil, &default_block) value = @hash[name][0] if @hash[name] if !value.nil? value elsif !default.nil? default elsif !default_block.nil? default_block.call else fail ArgumentError, "Value :#{name} is not set." end end |
#has?(name) ⇒ Boolean
Checks if value or callback is defined with specified name
38 39 40 |
# File 'lib/tablets/utils/config.rb', line 38 def has?(name) @hash[name].present? end |