Module: K::Configurable

Defined in:
lib/k/configurable.rb,
lib/k/configurable/version.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
'0.1.0'.freeze

Class Method Summary collapse

Class Method Details

.[](*attributes, **defaults, &block) ⇒ Object

Use ‘include Configurable [:foo, :bar]` to make your class/module configurable with configuration options :foo and :bar. If you want your configuration object to be able to respond to some custom methods you can extend it by passing a block. In that case you have to call `[]` like this include(Configurable.[](:foo) do

def bazinga
  ...
end

end) Because MRI cannot parse ‘Configurable {}`. Also keep in mind that the do-end block would get bound to `include` without the parens, you could also use {}-block instead, which binds tighter.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/k/configurable.rb', line 23

def self.[](*attributes, **defaults, &block)
  Module.new do
    @__attributes = (attributes + defaults.keys).uniq
    @__defaults = defaults
    @__block = block || -> {}

    def self.included(base)
      base.instance_variable_set(:@__configurable_attributes, @__attributes)
      base.instance_variable_set(:@__configurable_defaults, @__defaults)
      base.instance_variable_set(:@__configurable_block, @__block)
      base.extend(ClassMethods)
    end
  end
end

.included(_base) ⇒ Object



7
8
9
# File 'lib/k/configurable.rb', line 7

def self.included(_base)
  raise 'Cannot include Configurable, include Configurable::[] instead'
end