2018-10-12 16:59:02 -04:00
|
|
|
require "active_support/core_ext/hash/indifferent_access"
|
|
|
|
|
2017-10-20 15:20:28 -04:00
|
|
|
module FactoryBot
|
2011-01-25 17:55:40 -05:00
|
|
|
class Registry
|
2011-05-19 10:56:45 -04:00
|
|
|
include Enumerable
|
|
|
|
|
2012-04-20 23:49:37 -04:00
|
|
|
attr_reader :name
|
|
|
|
|
2011-10-15 01:54:01 -04:00
|
|
|
def initialize(name)
|
|
|
|
@name = name
|
2018-10-12 16:59:02 -04:00
|
|
|
@items = ActiveSupport::HashWithIndifferentAccess.new
|
2011-01-25 17:55:40 -05:00
|
|
|
end
|
|
|
|
|
2012-04-22 17:44:03 -04:00
|
|
|
def clear
|
|
|
|
@items.clear
|
|
|
|
end
|
|
|
|
|
|
|
|
def each(&block)
|
|
|
|
@items.values.uniq.each(&block)
|
2011-01-25 17:55:40 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def find(name)
|
2018-12-14 08:27:48 -05:00
|
|
|
@items.fetch(name)
|
|
|
|
rescue KeyError => key_error
|
|
|
|
raise key_error_with_custom_message(key_error)
|
2011-01-25 17:55:40 -05:00
|
|
|
end
|
|
|
|
|
2012-04-23 16:33:12 -04:00
|
|
|
alias :[] :find
|
|
|
|
|
2012-04-22 17:44:03 -04:00
|
|
|
def register(name, item)
|
2012-06-08 23:54:22 -04:00
|
|
|
@items[name] = item
|
2011-01-25 17:55:40 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def registered?(name)
|
2012-06-08 23:54:22 -04:00
|
|
|
@items.key?(name)
|
2011-01-25 17:55:40 -05:00
|
|
|
end
|
2018-12-14 08:27:48 -05:00
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def key_error_with_custom_message(key_error)
|
|
|
|
message = key_error.message.sub("key not found", "#{@name} not registered")
|
|
|
|
error = KeyError.new(message)
|
|
|
|
error.set_backtrace(key_error.backtrace)
|
|
|
|
error
|
|
|
|
end
|
2011-01-25 17:55:40 -05:00
|
|
|
end
|
|
|
|
end
|