Module: RSpecMagic::Stable::UseLetset::Exports

Defined in:
lib/rspec_magic/stable/use_letset.rb

Instance Method Summary collapse

Instance Method Details

#use_letset(let_method, collection_let) ⇒ void

Define the collection.

Parameters:

  • let_method (Symbol)
  • collection_let (Symbol)


48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rspec_magic/stable/use_letset.rb', line 48

def use_letset(let_method, collection_let)
  keys_m = "_#{collection_let}_keys".to_sym

  # See "Implementation notes" on failed implementation of "collection only" mode.

  # E.g. "_data_keys" or something.
  define_singleton_method(keys_m) do
    if instance_variable_defined?(k = "@#{keys_m}")
      instance_variable_get(k)
    else
      # Start by copying superclass's known vars or default to `[]`.
      instance_variable_set(k, (superclass.send(keys_m).dup rescue []))
    end
  end

  define_singleton_method let_method, ->(k, &block) do
    (send(keys_m) << k).uniq!
    # Create a `let` variable unless it's a declaration call (`let_a(:name)`).
    let(k, &block) if block
  end

  define_method(collection_let) do
    {}.tap do |h|
      self.class.send(keys_m).each do |k|
        h[k] = public_send(k) if respond_to?(k)
      end
    end
  end
end