Module: Alf::Support::Config::ClassMethods

Included in:
Alf::Support::Config
Defined in:
lib/alf/support/config.rb

Instance Method Summary collapse

Instance Method Details

#delegation_methodsObject


15
16
17
# File 'lib/alf/support/config.rb', line 15

def delegation_methods
  public_instance_methods(false).reject{|m| m.to_s =~ /=$/ }
end

#each_option(&bl) ⇒ Object


11
12
13
# File 'lib/alf/support/config.rb', line 11

def each_option(&bl)
  options.each(&bl)
end

#getter_name(option, domain) ⇒ Object


45
46
47
# File 'lib/alf/support/config.rb', line 45

def getter_name(option, domain)
  domain == Boolean ? :"#{option}?" : :"#{option}"
end

#helpers(to = :config) ⇒ Object


19
20
21
22
23
24
25
26
# File 'lib/alf/support/config.rb', line 19

def helpers(to = :config)
  meths = delegation_methods
  Module.new do
    meths.each do |m|
      define_method(m){|*args, &bl| self.send(to).send(m, *args, &bl) }
    end
  end
end

#ivar_name(option) ⇒ Object


53
54
55
# File 'lib/alf/support/config.rb', line 53

def ivar_name(option)
  :"@#{option}"
end

#option(name, domain, default_value) ⇒ Object


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/alf/support/config.rb', line 28

def option(name, domain, default_value)
  options << [name, domain, default_value]
  getter_name = self.getter_name(name, domain)
  setter_name = self.setter_name(name)
  ivar_name   = self.ivar_name(name)
  define_method(getter_name) do
    value = instance_variable_defined?(ivar_name) \
          ? instance_variable_get(ivar_name)
          : default_value
    value.is_a?(Proc) && domain != Proc ? instance_exec(&value) : value
  end
  define_method(setter_name) do |val|
    val = val.is_a?(Proc) ? val : Support.coerce(val, domain)
    instance_variable_set(ivar_name, val)
  end
end

#option_get(conf, name) ⇒ Object

Raises:


57
58
59
60
61
# File 'lib/alf/support/config.rb', line 57

def option_get(conf, name)
  option = options.find{|(n,_,_)| n == name }
  raise ConfigError, "No such option `#{name}`" unless option
  conf.send(getter_name(option[0], option[1]))
end

#option_set(conf, name, value) ⇒ Object

Raises:


63
64
65
66
67
# File 'lib/alf/support/config.rb', line 63

def option_set(conf, name, value)
  option = options.find{|(n,_,_)| n == name }
  raise ConfigError, "No such option `#{name}`" unless option
  conf.send(setter_name(option[0]), value)
end

#optionsObject


7
8
9
# File 'lib/alf/support/config.rb', line 7

def options
  @options ||= []
end

#setter_name(option) ⇒ Object


49
50
51
# File 'lib/alf/support/config.rb', line 49

def setter_name(option)
  :"#{option}="
end