Defining my own class of unique objects

J

jmay

Hi-

I'm trying to define a class with semantics similar to Fixnum, where
every object is unique. Each object has some internal state, more
complex that a single numeric value. Also, I want this to work across
marshalling and YAML.load. Semantics like this:

Foo.new("stuff").object_id == Foo.new("stuff").object_id
Foo.new("stuff").object_id ==
YAML.load(Foo.new("stuff").to_yaml).object_id

I looked at Memoize, but this just memoizes results of method calls on
instances, I couldn't figure out how to memoize #new.

I'm stumped. Any suggestions?

Thanks,
-Jason
 
A

ara.t.howard

Hi-

I'm trying to define a class with semantics similar to Fixnum, where every
object is unique. Each object has some internal state, more complex that a
single numeric value. Also, I want this to work across marshalling and
YAML.load. Semantics like this:

Foo.new("stuff").object_id == Foo.new("stuff").object_id

you can do this using

http://raa.ruby-lang.org/project/multiton/

or write your own based on

http://en.wikipedia.org/wiki/Multiton_pattern
Foo.new("stuff").object_id == YAML.load(Foo.new("stuff").to_yaml).object_id

dunno the yaml semantics, but this marshal example shows the pattern you will
need to follow using mashaling as an example:

harp:~ > cat a.rb
require 'multiton'

class Unique
include Multiton
def initialize *args
@args = args
end

def _dump *a
Marshal.dump @args, *a
end

def self._load buf
instance *(Marshal.load(buf))
end
end

p( Unique.instance(1,2).object_id == Unique.instance(1,2).object_id )
p( Unique.instance(1,2).object_id == Marshal.load(Marshal.dump(Unique.instance(1,2))).object_id )


harp:~ > ruby a.rb
true
true

regards.

-a
 
P

Phrogz

I'm trying to define a class with semantics similar to Fixnum, where
every object is unique. Each object has some internal state, more
complex that a single numeric value.

Smells like you want the (name under some discussion) Multiton
pattern:
http://rubyurl.com/qqw
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top