-
-
Save caius/1222712 to your computer and use it in GitHub Desktop.
Class typed methods in Ruby
This file contains hidden or 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
class Class | |
def define_typed_method(name, types, &block) | |
define_method(name) do |args| | |
args.each do |(arg, value)| | |
raise ArgumentError.new("Wrong class for #{arg}") unless value.is_a?(types[arg]) | |
end | |
block.call(args) | |
end | |
end | |
end | |
class MyThing | |
define_typed_method(:foo, bar: String, baz: Integer) do |args| | |
puts args[:bar] | |
puts args[:baz] | |
end | |
end | |
thing = MyThing.new | |
thing.foo(bar: "woof", baz: 123) | |
thing.foo(bar: "woof", baz: "123") # Boom! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment