SerialBox

Provides a simple, well-defined way to specify how your objects are serialized and deserialized into primitive types (say, for JSON serialization). Here's an example object:

class Car
  attr_accessor :seats, :color

  include SerialBox
  serialize_with :JSON
  serialize_fields do |s|
    s.serialize :seats
    s.serialize :color
  end
end

By calling serialize_with :JSON, your class now gets #to_json, #as_json, and .json_create methods making it work seamlessly with the json gem. If you have more complicated data structures or accessors, this gem works with that too:

class Color
  attr_accessor :r, :g, :b

  include SerialBox
  serialize_with :JSON
  serialize_fields do |s|
    s.serialize :r, :g, :b
  end
end

class Car
  attr_accessor :color # string

  include SerialBox
  serialize_with :JSON
  serialize_fields do |s|
    s.serializer 'color', :get_color
    s.deserializer 'color', :set_color
  end

  def get_color
    if color.r == 255 && color.g == 0 && color.b == 0
      'red'
    elsif color.r == 0 && color.g == 255 && color.b == 0
      'green'
    elsif color.r == 0 && color.g == 0 && color.b == 255
      'blue'
    end
  end

  def set_color(name)
    case name
      when 'red' then Color.new(255, 0, 0)
      when 'green' then Color.new(0, 255, 0)
      when 'blue' then Color.new(0, 0, 255)
    end
  end
end

The .serialize_fields method lets you define serializers and deserializers using simple to complex syntax, depending on your needs. Here are the supported syntaxes:

serialize_fields do |s|
  s.serialize :foo # uses #foo and #foo=, JSON field named "foo"
  s.serialize :foo, :into => 'bar' # uses #foo and #foo=, JSON field named "bar"
  s.serialize :@foo # reads and writes directly using @foo

  s.serializer 'foo', :bar # the JSON field "foo" will have the value returned by #bar
  s.deserializer 'foo', :bar= # the value in JSON field "foo" will be sent to #bar=

  s.serializer('foo') { bar.to_s } # the JSON field "foo" will have the value returned by the block
  s.deserializer('foo') { |value| self.bar = value.to_sym } # the block will be passed the value stored in JSON field "foo"; you must write it to your object
end

Important Note: Right now the only serializer implemented is :JSON. Other serializers should be easy to write by following its example.

Installation

To use, add this gem to your Gemfile:

gem 'serialbox'

then include the SerialBox module in your class, following one of the examples above.

Documentation

Comprehensive documentation is available by running rake doc.