Class: Class

Inherits:
Object
  • Object
show all
Defined in:
lib/json_serialisable.rb

Overview

Mixin for the Class class

Instance Method Summary collapse

Instance Method Details

#attr_serialise(*attrs) ⇒ Object

This way json_create will not error when it is called.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/json_serialisable.rb', line 15

def attr_serialise(*attrs)
   	
	# Sanity checks
	abort "Please provide at least one argument" if attrs.length == 0

	#Build to the to_json method
	tojson = "def to_json(*a)\n{ 'json_class' => #{self.name}"
	attrs.each { |a| tojson << ",\n'#{a}' => @#{a}"}
	tojson << "\n}.to_json(*a)\nend"

	#build to json_create method
	jsoncreate = "def self.json_create(o)\nnew( *o['#{attrs.shift}']"
	attrs.each { |a| jsoncreate << ", *o['#{a}']" }
	jsoncreate << ")\nend"

	# Add methods
	class_eval(tojson)
	class_eval(jsoncreate)
end