Module: Htmless::DynamicClasses

Included in:
Abstract
Defined in:
lib/htmless/dynamic_classes.rb

Overview

When extended into a class it enables easy defining and extending classes in the class.

class A extend DynamicClasses dynamic_classes do def_class :A do def to_s 'a' end end def_class :B, :A do class_eval <<-RUBYCODE, FILE, LINE+1 def to_s super + 'b' end RUBYCODE end end end

class B < A end

class C < A dynamic_classes do extend_class :A do def to_s 'aa' end end end end

puts A.dc[:A] # => #Class:0x00000001d449b8(A.dc[:A]) puts B.dc[:A] # => #Class:0x00000001d42398(B.dc[:A]) puts B.dc[:A].new # => a puts B.dc[:B].new # => ab puts C.dc[:B].new # => aab

Last example is the most interesting. It prints 'aab' not 'ab' because of the extension in class C. Class :B has as ancestor extended class :A from C therefore the two 'a'.

Defined Under Namespace

Modules: Describable Classes: ClassDefinition, ClassExtension, Classes, DescribableClass

Class Method Summary (collapse)

Instance Method Summary (collapse)

Class Method Details

+ (Object) extended(base)

hook to create Classes instance



180
181
182
183
# File 'lib/htmless/dynamic_classes.rb', line 180

def self.extended(base)
  base.send :create_dynamic_classes
  super
end

Instance Method Details

- (Object) create_dynamic_classes (private)



210
211
212
# File 'lib/htmless/dynamic_classes.rb', line 210

def create_dynamic_classes
  @dynamic_classes = Classes.new(self)
end

- (Classes) dynamic_classes {|Proc, nil| ... } Also known as: dc

call this to get access to Classes instance to define/extend classes inside +definition+ calls Classes#load! to preload defined classes a Proc enables writing class definitions/extensions

Yields:

  • (Proc, nil)

    definition

Returns:

  • (Classes)

    when definition is nil



196
197
198
199
200
201
202
203
204
# File 'lib/htmless/dynamic_classes.rb', line 196

def dynamic_classes(&definition)
  if definition
    @dynamic_classes.instance_eval &definition
    # @dynamic_classes.load!
    nil
  else
    @dynamic_classes
  end
end

- (Object) inherited(base)

hook to create Classes instance in descendants



186
187
188
189
# File 'lib/htmless/dynamic_classes.rb', line 186

def inherited(base)
  base.send :create_dynamic_classes
  super
end