Sha256: e917422e7298f302b6ac32f96ba8a3db9fa5e127dc74dda6dc99d7e1ee68b259

Contents?: true

Size: 1.19 KB

Versions: 19

Compression:

Stored size: 1.19 KB

Contents

#!/usr/local/bin/ruby -w
#
# == extensions/class.rb
#
# Adds methods to the builtin Class class. 
#

require "extensions/_base"

ExtensionsProject.implement(Class, :autoinit) do
  class Class
    #
    # A shorthand for the common chore of assigning initialize's parameters to
    # instance variables.  For example:
    #  
    #   class Circle
    #
    #     attr_reader :radius, :location, :area
    #
    #     autoinit(:radius, :location) do
    #       @area = Math::PI * @radius ** 2
    #     end
    #
    #   end
    #
    # A TypeError is raised unless all the arguments to +autoinit+ are strings
    # or symbols.
    #
    #--
    # Taken from ruby-talk:11668, by Avi Bryant.
    def autoinit(*args, &block) # :yield:
      unless args.all? { |a| Symbol === a or String === a }
        raise TypeError, "All arguments must be symbols or strings"
      end
      block = proc {} if block.nil?
      define_method(:__init_proc) { block }
      params = args.join(", ")
      vars = args.map { |a| "@#{a}" }.join(", ")

      code = %{
          def initialize(#{params})
            #{vars} = #{params}
            instance_eval(&__init_proc)
          end
        }
      class_eval code
    end
  end
end

Version data entries

19 entries across 19 versions & 4 rubygems

Version Path
extensions-0.5.0 lib/extensions/class.rb
extensions-0.6.0 lib/extensions/class.rb
glue-0.15.0 vendor/extensions/class.rb
glue-0.14.0 vendor/extensions/class.rb
glue-0.16.0 vendor/extensions/class.rb
glue-0.17.0 vendor/extensions/class.rb
nitro-0.11.0 vendor/extensions/class.rb
nitro-0.10.0 vendor/extensions/class.rb
nitro-0.12.0 vendor/extensions/class.rb
nitro-0.13.0 vendor/extensions/class.rb
nitro-0.9.5 vendor/extensions/class.rb
nitro-0.8.0 vendor/extensions/class.rb
nitro-0.9.3 vendor/extensions/class.rb
og-0.11.0 vendor/extensions/class.rb
og-0.10.0 vendor/extensions/class.rb
og-0.12.0 vendor/extensions/class.rb
og-0.8.0 vendor/extensions/class.rb
og-0.9.5 vendor/extensions/class.rb
og-0.9.3 vendor/extensions/class.rb