Last active
May 10, 2021 22:36
-
-
Save danhealy/1c18da4d4d67f243684994b38b9acdcd to your computer and use it in GitHub Desktop.
Automatically serialize a DragonRuby GTK class based on ivars
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 Serializable | |
# ... | |
# end | |
module Serializable | |
def inspect | |
serialize.to_s | |
end | |
def to_s | |
serialize.to_s | |
end | |
def serialize | |
attrs = Hash.new | |
instance_variables.each do |var| | |
str = var.to_s.gsub("@", '') | |
if respond_to? "#{str}=" | |
attrs[str.to_sym] = instance_variable_get var | |
end | |
end | |
attrs | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment