Class: Sham

Inherits:
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

.clearObject



25
26
27
# File 'lib/sham.rb', line 25

def self.clear
  @@shams = {}
end

.define(&block) ⇒ Object



33
34
35
# File 'lib/sham.rb', line 33

def self.define(&block)
  Sham.instance_eval(&block)
end

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



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

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.



7
8
9
10
11
12
13
# File 'lib/sham.rb', line 7

def self.name(*args, &block)
  if args.empty? && !block_given? && @@shams[:name].nil? # workaround for ZenTest initializer
    super
  else
    method_missing(:name, *args, &block)
  end
end

.reset(scope = :before_all) ⇒ Object



29
30
31
# File 'lib/sham.rb', line 29

def self.reset(scope = :before_all)
  @@shams.values.each { |sham| sham.reset(scope) }
end

Instance Method Details

#fetch_valueObject



55
56
57
58
59
60
61
62
63
64
# File 'lib/sham.rb', line 55

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
  result = @values[@offset]
  @offset += 1
  result
end

#reset(scope) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/sham.rb', line 45

def reset(scope)
  if scope == :before_all
    @offset, @before_offset = 0, nil
  elsif @before_offset
    @offset = @before_offset
  else
    @before_offset = @offset
  end
end