Flowdock

Chars enables you to work transparently with multibyte encodings in the Ruby <a href="/rails/String">String</a> class without having extensive knowledge about the encoding. A Chars object accepts a string upon initialization and proxies String methods in an encoding safe manner. All the normal String methods are also implemented on the proxy.

String methods are proxied through the Chars object, and can be accessed through the chars method. Methods which would normally return a String object now return a Chars object so methods can be chained.

  "The Perfect String  ".chars.downcase.strip.normalize # => "the perfect string"

Chars objects are perfectly interchangeable with String objects as long as no explicit class checks are made. If certain methods do explicitly check the class, call to_s before you pass chars objects to them.

  bad.explicit_checking_method "T".chars.downcase.to_s

The actual operations on the string are delegated to handlers. Theoretically handlers can be implemented for any encoding, but the default handler handles UTF-8. This handler is set during initialization, if you want to use you own handler, you can set it on the Chars class. Look at the UTF8Handler source for an example how to implement your own handler. If you your own handler to work on anything but UTF-8 you probably also want to override Chars#handler.

  ActiveSupport::Multibyte::Chars.handler = MyHandler

Note that a few methods are defined on Chars instead of the handler because they are defined on Object or Kernel and method_missing can’t catch them.

Aliases

  • string
Show files where this class is defined (1 file)
Register or log in to add new notes.