Class: Sham

Inherits:
Object
  • Object
show all
Defined in:
lib/sham.rb

Constant Summary collapse

@@shams =
{}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}, &block) ⇒ Sham

Returns a new instance of Sham.



37
38
39
40
41
42
43
# File 'lib/sham.rb', line 37

def initialize(name, options = {}, &block)
  @name      = name
  @generator = block
  @offset    = 0
  @unique    = options.has_key?(:unique) ? options[:unique] : true
  generate_values(12)
end

Class Method Details

.define(&block) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/sham.rb', line 27

def self.define(&block)
  definer = Object.new
  class << definer
    def method_missing(*args, &block)
      Sham.send(*args, &block)
    end
  end
  definer.instance_eval(&block)
end

.method_missing(symbol, *args, &block) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/sham.rb', line 13

def self.method_missing(symbol, *args, &block)
  if block_given?
    @@shams[symbol] = Sham.new(symbol, args.pop || {}, &block)
  else
    sham = @@shams[symbol]
    raise "No sham defined for #{symbol}" if sham.nil?
    sham.fetch_value
  end
end

.name(*args, &block) ⇒ Object

Over-ride module’s built-in name method, so we can re-use it for generating names. This is a bit of a no-no, but we get away with it in this context.



9
10
11
# File 'lib/sham.rb', line 9

def self.name(*args, &block)
  method_missing(:name, *args, &block)
end

.resetObject



23
24
25
# File 'lib/sham.rb', line 23

def self.reset
  @@shams.values.each(&:reset)
end

Instance Method Details

#fetch_valueObject



49
50
51
52
53
54
55
56
57
58
# File 'lib/sham.rb', line 49

def fetch_value
  # Generate more values if we need them.
  if @offset >= @values.length
    generate_values(2 * @values.length)
    raise "Can't generate more unique values for Sham.#{@name}" if @offset >= @values.length
  end
  returning @values[@offset] do
    @offset += 1
  end
end

#resetObject



45
46
47
# File 'lib/sham.rb', line 45

def reset
  @offset = 0
end