Defining my own class of unique objects


#1

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


#2

On Wed, 21 Mar 2007, jmay wrote:

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


#3

On Mar 20, 12:56 pm, “jmay” removed_email_address@domain.invalid wrote:

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


#4

On Mar 20, 12:44 pm, removed_email_address@domain.invalid wrote:

you can do this using

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

Multiton is exactly what I want. Thanks Ara!

To get it to work with YAML I needed to add a yaml_as declaration and
define self#yaml_new in my class, and that seems to have worked. I’m
not entirely satisfied with this solution, since it might break on
subclasses, but it’s good for now.

Cheers,
-Jason