How do I limit the object of any class to one. My class looks like :
class Speaker
include Mongoid::Document
field :name, :type => String
end
I just want to let a single instance of speaker . One way would be to add a validation which would check the number of objects already present of the Speaker class. Is there a ruby way of doing thing ?
A program may create many objects of the same class. Objects are also called instances, and they can be stored in either a named variable or in an array or collection. Client code is the code that uses these variables to call the methods and access the public properties of the object.
You can often avoid creating unnecessary objects by using static factory methods (Item 1) in preference to constructors on immutable classes that provide both. For example, the static factory method Boolean. valueOf(String) is almost always preferable to the constructor Boolean(String).
How about using the Singleton module?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With