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)
|
2020-06-05 15:15:18 -04:00
|
|
|
@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)
|
2019-05-12 22:39:55 -04:00
|
|
|
rescue KeyError => e
|
|
|
|
raise key_error_with_custom_message(e)
|
2011-01-25 17:55:40 -05:00
|
|
|
end
|
|
|
|
|
2020-06-05 15:15:18 -04:00
|
|
|
alias [] find
|
2012-04-23 16:33:12 -04:00
|
|
|
|
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
|