Sha256: 02a373e19741812a7cab2ecc4afdad503faa6447fd08b9abf75576027102b9da

Contents?: true

Size: 1.96 KB

Versions: 1

Compression:

Stored size: 1.96 KB

Contents

module PluginAWeek #:nodoc:
  module ModuleCreationHelper
    # Creates a new module with the specified name.  This is essentially the
    # same as actually defining the module like so:
    # 
    #   module NewModule
    #   end
    # 
    # or as a class:
    # 
    #   class NewClass < SuperKlass
    #   end
    # 
    # Configuration options:
    # <tt>superclass</tt> - The class to inherit from.  This only applies when using Class#create.  Default is Object.
    # <tt>parent</tt> - The class/module that contains this module.  Default is Object.
    # 
    # Examples:
    # 
    #   Module.create('Foo')                                                      # => Foo
    #   Module.create('Bar', :parent => Foo)                                      # => Foo::Bar
    #   Class.create('Waddle')                                                    # => Waddle
    #   Class.create('Widdle', :parent => Waddle)                                 # => Waddle::Widdle
    #   Class.create('Woddle', :superclass => Waddle::Widdle, :parent => Waddle)  # => Waddle::Woddle
    #   Waddle::Woddle.superclass                                                 # => Waddle::Widdle
    def create(name, options = {}, &block)
      options.assert_valid_keys(
        :superclass,
        :parent
      )
      raise ArgumentError, 'Modules cannot have superclasses' if options[:superclass] && self.to_s == 'Module'
      
      options.reverse_merge!(
        :superclass => Object,
        :parent => Object
      )
      parent = options[:parent]
      superclass = options[:superclass]
      
      if superclass != Object
        superclass = " < ::#{superclass}"
      else
        superclass = ''
      end
      
      parent.class_eval <<-end_eval
        #{self.to_s.downcase} #{name}#{superclass}
        end
      end_eval
      
      mod = parent.const_get(name)
      mod.class_eval(&block) if block_given?
      mod
    end
  end
end

Module.class_eval do
  extend PluginAWeek::ModuleCreationHelper
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
module_creation_helper-0.0.4 lib/module_creation_helper.rb