typecast.rb

Path: lib/more/facets/typecast.rb
Last Update: Mon Jun 01 21:54:17 -0400 2009

TypeCast

Provides a generic simple type conversion utility. All the ruby core conversions are available by default.

  "1234".cast_to Float     => 1234.0  (Float)
  Time.cast_from("6:30")   => 1234.0   (Time)

To implement a new type conversion, you have two choices, take:

 class CustomType
   def initialize(my_var)
     @my_var = my_var
   end
 end

Define a to_class_name instance method

 class CustomType
   def to_string
     my_var.to_s
   end
 end

 c = CustomType.new 1234
 s.cast_to String   =>  "1234" (String)

Define a from_class_name class method

 class CustomType
   def self.from_string(str)
     self.new(str)
   end
 end

 "1234".cast_to CustomType  =>  #<CustomType:0xb7d1958c @my_var="1234">

Those two methods are equivalent in the result. It was coded like that to avoid the pollution of core classes with tons of to_* methods.

The standard methods to_s, to_f, to_i, to_a and to_sym are also used by this system if available.

Faq

  1. Why didn‘t you name the `cast_to` method to `to` ?
  2. Even if it would make the syntax more friendly, I suspect it could cause

a lot of collisions with already existing code. The goal is that each time you call cast_to, you either get your result, either a TypeCastException

Authors

  • Jonas Pfenniger

History

  • 2006-06-06 3v1l_d4y:
    • Removed transformation options.
    • Removed StringIO typecast. It is not required by default.
    • Added TypeCastException for better error reporting while coding.

Todo

  • Consider how this might fit in with method signitures, overloading, and expiremental euphoria-like type system.
  • Look to implement to_int, to_mailtext, to_r, to_rfc822text and to_str.

Copying

  Copyright (c) 2004 Jonas Pfenniger

  Ruby License

  This module is free software. You may use, modify, and/or redistribute this
  software under the same terms as Ruby.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  FOR A PARTICULAR PURPOSE.

Required files

time   facets/string/methodize   facets/string/camelcase  

[Validate]