Skip to content

Instantly share code, notes, and snippets.

@ashmoran
Created September 16, 2011 17:48
Show Gist options
  • Save ashmoran/1222675 to your computer and use it in GitHub Desktop.
Save ashmoran/1222675 to your computer and use it in GitHub Desktop.
Class typed methods in Ruby
class Class
def define_class_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_class_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