Created
May 20, 2016 23:44
-
-
Save mbuffa/953c067b5025018c8470d5b77f245622 to your computer and use it in GitHub Desktop.
Hacky and dirty way to implement type hinting in ruby classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Author: Maxime Buffa <mbuffa@gmail.com> | |
# Copied from: https://github.com/mbuffa/ultima | |
# This module allow some sort of type hinting for instance methods. | |
# Set required variable types with #hint, and don't forget to call | |
# #hint_method(your_method_symbol) after its definition. | |
# It'll raise an ArgumentError if types mismatch. | |
module Hinting | |
@@hinting = Hash.new() | |
def self.extended(base) | |
base.class_eval do | |
define_singleton_method(:hint_method) do |method_symbol| | |
meth = instance_method(method_symbol) | |
define_method(method_symbol) do |*args, &block| | |
meth.parameters.map(&:last) | |
.each.with_index do |param_sym, i| | |
args.each.with_index do |arg, j| | |
# TODO: Find a better way than this... | |
next if i != j | |
type_hint = @@hinting[param_sym] | |
if !type_hint.nil? && type_hint != arg.class | |
raise ArgumentError, "#{param_sym} must be #{type_hint}" | |
end | |
end | |
end | |
meth.bind(self).call(*args, &block) | |
end | |
end | |
end | |
end | |
def hint(symbols, type) | |
Array(symbols).each do |param_sym| | |
@@hinting[param_sym] = type | |
end | |
end | |
def hinting | |
@@hinting | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
YourClass | |
extend Hinting | |
hint :a, String | |
hint :b, Fixnum | |
def initialize(a, b) | |
@a = a | |
@b = b | |
end | |
hint_method :initialize | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment