1
0
Fork 0
mirror of https://github.com/thoughtbot/factory_bot.git synced 2022-11-09 11:43:51 -05:00
thoughtbot--factory_bot/lib/factory_bot/registry.rb

48 lines
886 B
Ruby
Raw Normal View History

require "active_support/core_ext/hash/indifferent_access"
module FactoryBot
class Registry
include Enumerable
attr_reader :name
def initialize(name)
@name = name
@items = ActiveSupport::HashWithIndifferentAccess.new
end
2012-04-22 17:44:03 -04:00
def clear
@items.clear
end
def each(&block)
@items.values.uniq.each(&block)
end
def find(name)
@items.fetch(name)
rescue KeyError => e
raise key_error_with_custom_message(e)
end
alias [] find
2012-04-23 16:33:12 -04:00
2012-04-22 17:44:03 -04:00
def register(name, item)
@items[name] = item
end
def registered?(name)
@items.key?(name)
end
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
end
end