Sha256: 27d84551fe7045c7082e9405e2e82f7f05673af74d2ab3daf87197c98e8c108f

Contents?: true

Size: 1.61 KB

Versions: 4

Compression:

Stored size: 1.61 KB

Contents

class Class

  # get singleton methods to target class without super class methods
  def class_methods
    self.methods - Object.methods
  end

  # bind a singleton method to a class object
  def create_class_method(method,&block)
    self.class_eval do
      define_singleton_method method do |*args|
        block.call *args
      end
    end
  end

  # create an instance method
  def create_instance_method(method,&block)
    self.class_eval do
      define_method method do |*args|
        block.call *args
      end
    end
  end

  # Iterates over all subclasses (direct and indirect)
  def each_subclass
    ObjectSpace.each_object(Class) { | candidate |
      yield candidate if candidate < self
    }
  end

  # Returns an Array of subclasses (direct and indirect)
  def subclasses
    ret = []
    each_subclass {|c| ret << c}
    ret
  end

  # Returns an Array of direct subclasses
  def direct_subclasses
    ret = []
    each_subclass {|c| ret << c if c.superclass == self }
    ret
  end

  # create singleton attribute
  def class_attr_accessor(name)

    ### GET
    begin
      define_method name do
        class_variable_get "@@#{name}"
      end
    end

    ### SET
    begin
      define_method "#{name}=" do |new_val|
        class_variable_set "@@#{name}", new_val
      end
    end

  end

  # create class instance attribute
  def instance_attr_accessor(name)

    ### GET
    begin
      define_method name do
        instance_variable_get "@#{name}"
      end
    end

    ### SET
    begin
      define_method "#{name}=" do |new_val|
        instance_variable_set "@#{name}", new_val
      end
    end

  end

end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
procemon-0.0.4 lib/procemon/mpatch/class.rb
procemon-0.0.3 lib/procemon/mpatch/class.rb
procemon-0.0.2 lib/procemon/mpatch/class.rb
procemon-0.0.1 lib/procemon/mpatch/class.rb