D
Daniel Schierbeck
This will make it easier to add type checking to your methods. Let me
know if you think the method belongs in Object or another class, rather
than in the Kernel module.
class Kernel
def cast(obj, klass, method = nil)
return obj if obj.kind_of? klass
method = "to_#{method || klass.downcase}"
unless obj.respond_to? method
raise TypeError, "Can't convert #{obj.class} into #{klass}"
end
cast_obj = obj.send(method)
unless ccast_obj.kind_of? klass
raise TypeError, "#{obj.class}##{method} should return #{klass}"
end
return cast_obj
end
end
class Klass
def foo(arg)
# Will raise an exception unless `arg' is
# of type SomeKlass, or if it has a method
# #to_some_klass that returns an object of
# type SomeKlass
arg = cast(arg, SomeKlass, :some_klass)
end
end
Is there an easy way to turn a CapitalizedName into a downcase_name?
Right now I'm just downcasing the class name if no cast method name is
explicitly provided, but I'm not sure that's enough.
Cheers,
Daniel
know if you think the method belongs in Object or another class, rather
than in the Kernel module.
class Kernel
def cast(obj, klass, method = nil)
return obj if obj.kind_of? klass
method = "to_#{method || klass.downcase}"
unless obj.respond_to? method
raise TypeError, "Can't convert #{obj.class} into #{klass}"
end
cast_obj = obj.send(method)
unless ccast_obj.kind_of? klass
raise TypeError, "#{obj.class}##{method} should return #{klass}"
end
return cast_obj
end
end
class Klass
def foo(arg)
# Will raise an exception unless `arg' is
# of type SomeKlass, or if it has a method
# #to_some_klass that returns an object of
# type SomeKlass
arg = cast(arg, SomeKlass, :some_klass)
end
end
Is there an easy way to turn a CapitalizedName into a downcase_name?
Right now I'm just downcasing the class name if no cast method name is
explicitly provided, but I'm not sure that's enough.
Cheers,
Daniel