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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

It's nice that your suggested method initializes AND returns the value.
Another good thing I found: ActiveSupport's class_attribute function (in active_support/core_ext/class/attribute).
If you are using rails then that is a good solution (be careful not to unintentionally update the attribute in place though)
I'm using it without Rails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.