Skip to content

Instantly share code, notes, and snippets.

@rklemme
Last active May 12, 2017 15:49
Show Gist options
  • Select an option

  • Save rklemme/7213313 to your computer and use it in GitHub Desktop.

Select an option

Save rklemme/7213313 to your computer and use it in GitHub Desktop.

Revisions

  1. rklemme revised this gist Oct 29, 2013. 1 changed file with 13 additions and 12 deletions.
    25 changes: 13 additions & 12 deletions automated_class_instance_collaboration.rb
    Original file line number Diff line number Diff line change
    @@ -2,26 +2,27 @@

    module Foo
    module Foo4Class
    def reset_instance_count
    @instance_count = 0
    end

    def new(*a, &b)
    super.tap { @instance_count += 1 }
    end

    def instance_count
    @instance_count
    end
    end

    def self.included(cl)
    cl.extend Foo4Class

    cl.instance_variable_set '@instance_count', 0

    cl.singleton_class.class_eval do
    def new(*a,&b)
    super.tap { @instance_count += 1 }
    end
    end
    end

    def shout_instance_count
    printf "There have been %d of us created!\n", self.class.instance_count
    end

    # setup mechanics
    def self.included(cl)
    cl.extend(Foo4Class).reset_instance_count
    end
    end


  2. rklemme revised this gist Oct 29, 2013. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion automated_class_instance_collaboration.rb
    Original file line number Diff line number Diff line change
    @@ -29,4 +29,4 @@ class Bar
    include Foo
    end

    Array.new(10) { Bar.new }.first.shout_instance_count
    Array.new(10) { Bar.new }.each(&:shout_instance_count)
  3. rklemme created this gist Oct 29, 2013.
    32 changes: 32 additions & 0 deletions automated_class_instance_collaboration.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,32 @@
    #!/usr/bin/ruby -w

    module Foo
    module Foo4Class
    def instance_count
    @instance_count
    end
    end

    def self.included(cl)
    cl.extend Foo4Class

    cl.instance_variable_set '@instance_count', 0

    cl.singleton_class.class_eval do
    def new(*a,&b)
    super.tap { @instance_count += 1 }
    end
    end
    end

    def shout_instance_count
    printf "There have been %d of us created!\n", self.class.instance_count
    end
    end


    class Bar
    include Foo
    end

    Array.new(10) { Bar.new }.first.shout_instance_count