Last active
August 29, 2015 14:18
-
-
Save tiagopog/f9e95dfa3573a3d8baba to your computer and use it in GitHub Desktop.
Marshal/Unmarshal example in Ruby.
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
require 'base64' | |
# Let's first create a non primitive class that will be dumped. | |
class People | |
POSSIBLE_NAMES = %w(foo bar) | |
@@count = 0 | |
def initialize(*attrs) | |
@@count += 1 | |
@name = attrs[0] || 'Foo' | |
@last_name = attrs[1] || 'Bar' | |
puts 'New people in da house!' | |
end | |
def self.count | |
"Total: #{@@count}" | |
end | |
def full_name | |
if are_names_ok?(@name, @last_name) | |
"Full name: #{@name} #{@last_name}" | |
else | |
"Sorry, you have a bad name." | |
end | |
end | |
private | |
def are_names_ok?(*names) | |
names.all? { |name| POSSIBLE_NAMES.include?(name.downcase) } | |
end | |
end | |
# Now let's create a singleton class to storage our objects. | |
class Database | |
@@collection = [] | |
class << self | |
def collection; @@collection end | |
def store(data) | |
@@collection << data | |
puts "New object stored into the database: #{data}" | |
end | |
end | |
end | |
# Then let's start with the example... | |
people = People.new | |
puts people.full_name | |
puts People.count | |
token = Base64.encode64(Marshal.dump(people)) | |
Database.store(token) | |
puts Database.collection | |
people = Marshal.load(Base64.decode64(Database.collection.first)) | |
puts people.full_name | |
puts People.count |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment