Skip to content

Instantly share code, notes, and snippets.

@ksss
Last active May 27, 2017 00:42
Show Gist options
  • Save ksss/42671582f9b5b5f29f5f4eb74836278c to your computer and use it in GitHub Desktop.
Save ksss/42671582f9b5b5f29f5f4eb74836278c to your computer and use it in GitHub Desktop.
module TypeChecker
Error = Class.new(StandardError)
class << self
def register(this, meth, klass)
this.module_eval(<<~RUBY, __FILE__, __LINE__ + 1)
def #{meth}
ret = super
unless ret.kind_of?(#{klass})
raise Error, "no implicit conversion of \#{self.class} into #{klass} got \#{ret.class}"
end
end
RUBY
end
end
end
module TypeChecker
module Standard
{
to_i: Integer,
to_int: Integer,
to_f: Float,
to_s: String,
to_str: String,
to_sym: Symbol,
to_h: Hash,
to_hash: Hash,
to_a: Array,
to_io: IO,
}.each do |m, c|
TypeChecker.register(self, m, c)
end
end
end
class A
prepend TypeChecker::Standard
def to_h
[]
end
end
begin
A.new.to_h
rescue TypeChecker::Error
else
raise
end
begin
A.new.to_a
rescue NoMethodError
else
raise
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment