Module: Zif::Serializable

Overview

A mixin for automatically definining #serialize based on instance variables with setter methods

If you have circular references in ivars (Foo.bar <-> Bar.foo), make sure one of the classes overrides #exclude_from_serialize and specifies the attr.

Examples:

# Throw this file into your app folder, like app/lib/serializable.rb

# In your main.rb or wherever you require files:
require 'app/lib/serializable.rb'

# In each class you want to automatically serialize:
class Foo
  include Zif::Serializable
  ...
end

Instance Method Summary collapse

Instance Method Details

#exclude_from_serializeArray<Symbol>

In the included class, override this method to exclude attrs from serialization / printing

Returns:

  • (Array<Symbol>)

    Names of attributes to exclude from serialization



43
44
45
# File 'lib/zif/serializable.rb', line 43

def exclude_from_serialize
  %w[args] # Too much spam
end

#inspectString

Returns Convert #serialize to string.

Returns:



20
21
22
# File 'lib/zif/serializable.rb', line 20

def inspect
  serialize.to_s
end

#serializeHash<Symbol, Object>

Returns Convert #serialize to string.

Returns:

  • (Hash<Symbol, Object>)

    Convert #serialize to string



30
31
32
33
34
35
36
37
38
39
# File 'lib/zif/serializable.rb', line 30

def serialize
  attrs = {}
  instance_variables.each do |var|
    str = var.to_s.gsub('@', '')
    next if exclude_from_serialize.include? str

    attrs[str.to_sym] = instance_variable_get var if respond_to? "#{str}="
  end
  attrs
end

#to_sString

Returns Convert #serialize to string.

Returns:



25
26
27
# File 'lib/zif/serializable.rb', line 25

def to_s
  serialize.to_s
end