File: singleton.rb

package info (click to toggle)
ruby-ftw 0.0.49-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 548 kB
  • sloc: ruby: 1,922; makefile: 5
file content (38 lines) | stat: -rw-r--r-- 878 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
require "ftw/namespace"

# A mixin that provides singleton-ness
#
# Usage:
#
#     class Foo
#       extend FTW::Singleton
#
#       ...
#     end
#
# foo = Foo.singleton
module FTW::Singleton
  # This is invoked when you include this module. It raises an exception because you should be
  # using 'extend' not 'include' for this module..
  def self.included(klass)
    raise ArgumentError.new("In #{klass.name}, you want to use 'extend #{self.name}', not 'include ...'")
  end # def included

  # Create a singleton instance of whatever class this module is extended into.
  #
  # Example:
  #
  #     class Foo
  #       extend FTW::Singleton
  #       def bar
  #         "Hello!"
  #       end
  #     end
  #
  #     p Foo.singleton.bar   # == "Hello!"
  def singleton
    @instance ||= self.new
    return @instance
  end # def self.singleton
end # module FTW::Singleton