configurable.rb 1.5 KB
Newer Older
1 2 3 4
require 'active_support/concern'
require 'active_support/ordered_options'
require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/module/delegation'
5 6

module ActiveSupport
7 8
  # Configurable provides a <tt>config</tt> method to store and retrieve
  # configuration options as an <tt>OrderedHash</tt>.
9 10 11 12 13
  module Configurable
    extend ActiveSupport::Concern

    module ClassMethods
      def config
14
        @_config ||= ActiveSupport::InheritableOptions.new(superclass.respond_to?(:config) ? superclass.config : {})
15 16
      end

17 18 19 20 21 22 23 24 25 26 27 28 29
      def configure
        yield config
      end

      def config_accessor(*names)
        names.each do |name|
          code, line = <<-RUBY, __LINE__ + 1
            def #{name}; config.#{name}; end
            def #{name}=(value); config.#{name} = value; end
          RUBY

          singleton_class.class_eval code, __FILE__, line
          class_eval code, __FILE__, line
30 31 32 33
        end
      end
    end

34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
    # Reads and writes attributes from a configuration <tt>OrderedHash</tt>.
    # 
    #   require 'active_support/configurable'      
    #  
    #   class User
    #     include ActiveSupport::Configurable
    #   end 
    #
    #   user = User.new
    # 
    #   user.config.allowed_access = true
    #   user.config.level = 1
    #
    #   user.config.allowed_access # => true
    #   user.config.level          # => 1
    # 
50
    def config
51
      @_config ||= ActiveSupport::InheritableOptions.new(self.class.config)
52 53
    end
  end
54 55
end