1

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
Community
  • 1
  • 1
Dor
  • 902
  • 4
  • 24

1 Answers1

1

Class instance variables are not inherited, so the line

@serializable_attrs = {}

Only sets this in Serializable not its subclasses. While you could use the inherited hook to set this on subclassing or change the serialize method to initialize @serializable_attrs I would probably add

def self.serializable_attrs
  @serializable_attrs ||= {}
end

And then use that rather than referring directly to the instance variable.

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174