Sha256: 3cf37d44c748c0f57ecad6d0254150b9ba1bc2ebb8d4df984827fe30cf05f218

Contents?: true

Size: 1.25 KB

Versions: 1

Compression:

Stored size: 1.25 KB

Contents

require "active_support/core_ext/class/attribute"
require "active_support/concern"
require "new_class/version" unless defined?(NewClass::VERSION)

module NewClass

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def new_class(variables = {}, name = nil)
      Class.new(self).tap do |klass|
        klass.send :include, Concerns, MethodMissing
        klass.extend MethodMissing
        klass._name = name || self.name
        klass._variables = variables.inject({}){|h, (k, v)| h.merge k.to_sym => v}
        klass.defined if klass.respond_to?(:defined)
      end
    end

    module Concerns
      extend ActiveSupport::Concern
      included do
        class_attribute :_name, :_variables
      end
      module ClassMethods
        def name
          _name || super
        end
        alias :to_s :name
      end
      module InstanceMethods
        def _variables
          self.class._variables
        end
      end
    end

    module MethodMissing
      def method_missing(method, *args)
        _variables.include?(key = method.to_sym) ? define_method(key){ _variables[key] }.call : super
      end
      def respond_to?(symbol, include_private = false)
        _variables.include?(symbol.to_sym) || super
      end
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
new_class-0.1.0 lib/new_class.rb