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.
Example
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
end
end
attr_serialisable would generate the following methods:
def to_json(*a)
{
"json_class" => self.class.name,
"a" => @a,
"b" => @b,
"c" => @c
}.to_json(*a)
end
def json_create(o)
new(*o["a"], *o["b"], *o["c"])
end
Which will allow the class to easily be used by the ‘json’ library.