Module: TcravitRubyLib::Configurable

Defined in:
lib/tcravit_ruby_lib/configurable.rb

Overview

Make a class configurable via a DSL

From www.toptal.com/ruby/ruby-dsl-metaprogramming-guide

Sample Usage:

class MyApp

include Configurable.with(:app_id, :title, :cookie_name)

# ...

end

SomeClass.configure do

app_id "my_app"
title "My App"
cookie_name { "#{app_id}_session" }

end

Class Method Summary collapse

Class Method Details

.with(*attrs) ⇒ Object

nodoc



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/tcravit_ruby_lib/configurable.rb', line 45

def self.with(*attrs)
  not_provided = Object.new
  config_class = Class.new do
    attrs.each do |attr|
      define_method attr do |value = not_provided, &block|
        if value === not_provided && block.nil?
          result = instance_variable_get("@#{attr}")
          result.is_a?(Proc) ? instance_eval(&result) : result
        else
          instance_variable_set("@#{attr}", block || value)
        end
      end
    end
    attr_writer *attrs
  end
  class_methods = Module.new do
    define_method :config do
      @config ||= config_class.new
    end
    def configure(&block)
      config.instance_eval(&block)
    end
  end
  Module.new do
    singleton_class.send :define_method, :included do |host_class|
      host_class.extend class_methods
    end
  end
end