# make class convertable to JSON format (unused in this snippet)
class JSONable
def to_json
hash = {}
self.instance_variables.each do |var|
hash[var] = self.instance_variable_get var
end
hash.to_json
end
def from_json! string
JSON.load(string).each do |var, val|
self.instance_variable_set var, val
end
end
end
class Object
def self.inherited(klass)
def klass.method_added(name)
return if @_not_new
@_not_new = true
original = "original #{name}"
alias_method original, name
puts "#{name}"
define_method(name) do |*args, &block|
puts "==> called #{name} with args: #{args.inspect}"
result = send original, *args, &block
puts "<== result is #{result}"
result
end
@_not_new = false
end
end
# serialize object to JSON format
define_method :tojson do
# get all instance variables
ivar = instance_variables.each_with_object({}) { |var, hash| hash[var.to_s.delete("@")] = instance_variable_get(var) }
# get all class variables (static var)
cvar = self.class.class_variables.each_with_object({}) { |var, hash| hash[var.to_s.delete("@")] = self.class.class_variable_get(var) }
# merge it into one hash
ivar.merge!(cvar)
end
end
class Product # < JSONable
@@ss = 100 # static
def self.sides
@ss
end
def meth(a1, a2)
@value = 10
@string = "10"
a1 + a2
end
end
product = Product.new
puts product.meth(2,3)
# hash = product.instance_variables.each_with_object({}) { |var, hash| hash[var.to_s.delete("@")] = product.instance_variable_get(var) }
# p hash # => {"name"=>"book", "price"=>15.95}
product.tojson
puts "OR DO it another way"
require 'oj'
class Foo
def initialize()
@aMemberVar = 'aMemberVar Member Variable'
@aFuncName = 'aMemberFunc'
@__pr = 'private'
end
end
foo = Foo.new
puts Oj.dump foo
# product.class.instance_variables
# puts Product.class_variables