Ruby gem – json_serialisable

I was working on a ruby project and stumbed upon my first valid application of metaprogramming. I was creating json serialisation methods and realised they were all practically identical. So I looked at how attr_accessor worked and then wrote my own class method called attr_serialisable. This method generated serialisation methods automatically.


Given a class A

class A
  attr_accessor :a, :b, :c
  attr_serialisable :a, :b, :c

  def initialize(a, b, c)
    @a, @b, @c = a, b, c


attr_serialisable would generate the following methods:

  def to_json(*a)
      "json_class"  =>,
      "a"           =>  @a,
      "b"           =>  @b,
      "c"           =>  @c

  def json_create(o)
    new(*o["a"], *o["b"], *o["c"])


Which will allow the class to easily be used by the ‘json’ library.


Rubygems page
Source code

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.