Relying on this answer, I wrote the following class. When using it, I get an error:
in 'serialize': undefined method '[]=' for nil:NilClass (NoMethodError).
How can I access the variable @serializable_attrs
in a base class?
Base class:
# Provides an attribute serialization interface to subclasses.
class Serializable
@serializable_attrs = {}
def self.serialize(name, target=nil)
attr_accessor(name)
@serializable_attrs[name] = target
end
def initialize(opts)
opts.each do |attr, val|
instance_variable_set("@#{attr}", val)
end
end
def to_hash
result = {}
self.class.serializable_attrs.each do |attr, target|
if target != nil then
result[target] = instance_variable_get("@#{attr}")
end
end
return result
end
end
Usage example:
class AuthRequest < Serializable
serialize :company_id, 'companyId'
serialize :private_key, 'privateKey'
end