Skip to content

Instantly share code, notes, and snippets.

@cookrn
Last active January 2, 2016 21:59
Show Gist options
  • Select an option

  • Save cookrn/8367449 to your computer and use it in GitHub Desktop.

Select an option

Save cookrn/8367449 to your computer and use it in GitHub Desktop.

Revisions

  1. cookrn revised this gist Jan 11, 2014. 1 changed file with 45 additions and 3 deletions.
    48 changes: 45 additions & 3 deletions b.rb
    Original file line number Diff line number Diff line change
    @@ -4,15 +4,57 @@ def deftyped( method_name , method_arg_defns , &block )
    self,
    method_name,
    method_arg_defns,
    block
    &block

    define_method method_name do | *args , &block |
    TypedMethod.call \
    self,
    method_name,
    *args,
    block,
    binding
    binding,
    &block
    end
    end
    end

    class TypedMethod
    def self.call( object , method_name , *args , binding , &block )
    id = id_for object , method_name
    typed_method = Thread.current[ id ]
    raise NoMethodError unless typed_method

    typed_method.call \
    *args,
    binding,
    &block
    end

    def self.id_for( object , method_name )
    real_object =
    if object.ancestors.include? Class
    object
    else
    object.class
    end

    :"#{ real_object.name }_#{ method_name }"
    end

    def self.register( object , method_name , method_arg_defns , &block )
    id = id_for object , method_name
    Thread.current[ id ] =
    new \
    object,
    method_name,
    method_arg_defns,
    &block
    end

    def initialize( *args , &block )
    # do stuff
    end

    def call( *args , &block )
    # do stuff
    end
    end
  2. cookrn revised this gist Jan 11, 2014. 1 changed file with 18 additions and 0 deletions.
    18 changes: 18 additions & 0 deletions b.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    class Object
    def deftyped( method_name , method_arg_defns , &block )
    TypedMethod.register \
    self,
    method_name,
    method_arg_defns,
    block

    define_method method_name do | *args , &block |
    TypedMethod.call \
    self,
    method_name,
    *args,
    block,
    binding
    end
    end
    end
  3. cookrn created this gist Jan 11, 2014.
    11 changes: 11 additions & 0 deletions a.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    class Printer
    attr_reader :printer

    deftyped :initialize , :printer => [ Proc ] do
    @printer = printer
    end

    deftyped :print , :string => { :splat => true , :type => String } do
    printer.call string.join( ' ' )
    end
    end