U:RDoc::NormalModule[iI"Singleton:EF@0o:RDoc::Markup::Document: @parts[o;;[o:RDoc::Markup::Paragraph;[I";The Singleton module implements the Singleton pattern.;To:RDoc::Markup::BlankLineS:RDoc::Markup::Heading: leveli: textI" Usage;T@o; ;[I"8To use Singleton, include the module in your class.;T@o:RDoc::Markup::Verbatim;[ I"class Klass ;TI" include Singleton ;TI" # ... ;TI" end ;T: @format0o; ;[I"AThis ensures that only one instance of Klass can be created.;T@o;;[ I"+a,b = Klass.instance, Klass.instance ;TI" ;TI" a == b ;TI"# => true ;TI" ;TI"Klass.new ;TI"-# => NoMethodError - new is private ... ;T;0o; ;[I"HThe instance is created at upon the first call of Klass.instance().;T@o;;[I"class OtherKlass ;TI" include Singleton ;TI" # ... ;TI" end ;TI" ;TI"+ObjectSpace.each_object(OtherKlass){} ;TI" # => 0 ;TI" ;TI"OtherKlass.instance ;TI"+ObjectSpace.each_object(OtherKlass){} ;TI" # => 1 ;T;0o; ;[I">This behavior is preserved under inheritance and cloning.;T@S; ; i; I"Implementation;T@o; ;[I"This above is achieved by:;T@o:RDoc::Markup::List: @type: BULLET: @items[ o:RDoc::Markup::ListItem: @label0;[o; ;[I"1Making Klass.new and Klass.allocate private.;T@o;;0;[o; ;[I"POverriding Klass.inherited(sub_klass) and Klass.clone() to ensure that the ;TI"=Singleton properties are kept when inherited and cloned.;T@o;;0;[o; ;[I"MProviding the Klass.instance() method that returns the same object each ;TI"time it is called.;T@o;;0;[o; ;[I":Overriding Klass._load(str) to call Klass.instance().;T@o;;0;[o; ;[I"IOverriding Klass#clone and Klass#dup to raise TypeErrors to prevent ;TI"cloning or duping.;T@S; ; i; I"Singleton and Marshal;T@o; ;[ I"SBy default Singleton's #_dump(depth) returns the empty string. Marshalling by ;TI"Mdefault will strip state information, e.g. instance variables and taint ;TI"Jstate, from the instance. Classes using Singleton can provide custom ;TI"Q_load(str) and _dump(depth) methods to retain some of the previous state of ;TI"the instance.;T@o;;["I"require 'singleton' ;TI" ;TI"class Example ;TI" include Singleton ;TI"# attr_accessor :keep, :strip ;TI" def _dump(depth) ;TI"@ # this strips the @strip information from the instance ;TI"$ Marshal.dump(@keep, depth) ;TI" end ;TI" ;TI" def self._load(str) ;TI"+ instance.keep = Marshal.load(str) ;TI" instance ;TI" end ;TI" end ;TI" ;TI"a = Example.instance ;TI"a.keep = "keep this" ;TI"!a.strip = "get rid of this" ;TI" a.taint ;TI" ;TI"$stored_state = Marshal.dump(a) ;TI" ;TI"a.keep = nil ;TI"a.strip = nil ;TI"$b = Marshal.load(stored_state) ;TI"p a == b # => true ;TI"!p a.keep # => "keep this" ;TI"p a.strip # => nil;T;0: @fileI"lib/singleton.rb;T:0@omit_headings_from_table_of_contents_below0;0;0[[[[[I" class;T[[: public[[I" _load;TI"lib/singleton.rb;T[:protected[[: private[[I"append_features;F@Œ[I" included;F@Œ[I" instance;T[[;[[I" _dump;F@Œ[I" clone;F@Œ[I"dup;F@Œ[;[[;[[[I"SingletonClassMethods;To;;[;@€;0@Œ[U:RDoc::Context::Section[i0o;;[;0;0[@€@€cRDoc::TopLevel