Class: Tablets::Utils::Config

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(&block) ⇒ Config

Initializes config with block. Block is optional and can be applied later.



24
25
26
27
28
# File 'lib/tablets/utils/config.rb', line 24

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.



75
76
77
# File 'lib/tablets/utils/config.rb', line 75

def method_missing(name, *args, &block)
  @hash[name] = [*args, block]
end

Instance Method Details

#apply(&block) ⇒ Object

Executes block in config context.



31
32
33
# File 'lib/tablets/utils/config.rb', line 31

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.



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/tablets/utils/config.rb', line 60

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.



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/tablets/utils/config.rb', line 43

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.

Returns:

  • (Boolean)


36
37
38
# File 'lib/tablets/utils/config.rb', line 36

def has?(name)
  @hash[name].present?
end