Sha256: 1a54dffb7544f50c95555b08e68a89e3bc765a166469013f1c6cfc45189282e3

Contents?: true

Size: 1.66 KB

Versions: 5

Compression:

Stored size: 1.66 KB

Contents

# -*- encoding : utf-8 -*-
require 'singleton'
require 'forwardable'

module Exchange
  
  class Configurable
    include Singleton
    extend SingleForwardable
    
    attr_accessor :subclass
    
    def_delegators :instance, :subclass, :subclass=, :set
    
    # Alias method chain to instantiate the subclass from a symbol should it not be a class
    # @return [NilClass, Class] The subclass or nil
    #
    def subclass_with_constantize
      self.subclass = parent_module.const_get camelize(self.subclass_without_constantize) unless !self.subclass_without_constantize || self.subclass_without_constantize.is_a?(Class)
      subclass_without_constantize
    end
    alias_method :subclass_without_constantize, :subclass
    alias_method :subclass, :subclass_with_constantize
    
    # Set a configuration via a hash of options
    # @params [Hash] hash The hash of options to set the configuration to
    #
    def set hash
      hash.each_pair do |k,v|
        self.send(:"#{k}=", v)
      end
      
      self
    end
    
    # Reset the configuration to a set of defaults
    #
    def reset
      set Exchange::Configuration::DEFAULTS[key]
    end
    
    [:key, :parent_module].each do |subclass_method|
      define_method subclass_method do
        raise StandardError.new("Subclass Responsibility")
      end
    end
    
    private

      # Camelize a string or a symbol
      # @param [String, Symbol] s The string to camelize
      # @return [String] a camelized string
      # @example Camelize an underscored symbol
      #   camelize(:some_thing) #=> "SomeThing"
      #
      def camelize s
        s = s.to_s.gsub(/(?:^|_)(.)/) { $1.upcase }
      end
    
  end
  
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
exchange-1.2.2 lib/exchange/configurable.rb
exchange-1.2.1 lib/exchange/configurable.rb
exchange-1.2.0 lib/exchange/configurable.rb
exchange-1.1.1 lib/exchange/configurable.rb
exchange-1.1.0 lib/exchange/configurable.rb