Welcome to Formatted Strings

The purpose of this gem is to provide functions for the String object that are related to different but standard formats. Example formats include: XML, HTML & JSON, but also simple formats like email address, phone number, or street address. Any format whose logic can be programmed can be included in this list, but you might have to program those functions yourself. See Extending for more information.

Usage

Simply include this gem in your project:

require 'rubygems'
gem 'formattedstring'

s = '<some><xml>text</xml></some>'
s.format
=> nil
s.format = :xml
s.format
=> :xml
s.to_hash
=> {'some' => {'xml' => 'text'}}

You can, in fact, set a format more than once. If your string is valid XML, but also valid HTML, you may want to include both sets of methods on your string. Simply call ‘format=’ twice, and you will have a doubly-formatted string.

Extending

The way this gem works is this: On initialization of the gem, FormattedStrings adds two methods to the String class: ‘format’ and ‘format=’. When ‘format=’ is called, the value sent to it is used to require a file that should contain a module by the same name, and extend the string object by that module. For example:

module FormattedString
  module Formats
    module Xml
      def to_hash
        # . . .
      end
    end
  end
end

s = '<some><xml>text</xml></some>'
s.format = :xml
# => require 'formatted_string/formats/xml'
# => s.extend FormattedString::Formats::Xml

The require is held behind a silent rescue, so to add your own formats, just create a module within the FormattedString::Formats namespace, with the module name the camelcase version of what you want to set your format to. In other words, a module like the Xml example above could be in any file as long as it was require’d into your project before calling ‘format = :xml’.

Download

Status

Open to contributions. Please email [email protected] with your suggestions, code, format adapters, or whatever else you wish.

Author

This library is released under the terms of the MIT License.

Changelog

0.1.0 Simple and Stable. Included XML and YAML formats. 0.1.1 Adds JSON format.