module TcravitRubyLib::Configurable

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

Public Class Methods

with(*attrs) click to toggle source

nodoc

# 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

Public Instance Methods

configure(&block) click to toggle source
# File lib/tcravit_ruby_lib/configurable.rb, line 64
def configure(&block)
  config.instance_eval(&block)
end