Class: Identitee::Identifiables

Inherits:
Object
  • Object
show all
Defined in:
lib/identitee/identifiables.rb

Instance Method Summary collapse

Constructor Details

#initializeIdentifiables

Returns a new instance of Identifiables.



6
7
8
9
10
# File 'lib/identitee/identifiables.rb', line 6

def initialize 
  @instances = {}
  @loaders = []
  @all_loaded = false
end

Instance Method Details

#add_loader(loader) ⇒ Object



12
13
14
# File 'lib/identitee/identifiables.rb', line 12

def add_loader loader
  loaders << loader
end

#allObject



40
41
42
43
# File 'lib/identitee/identifiables.rb', line 40

def all
  load_all unless all_loaded
  instances.values
end

#find(key, *default_values, &block) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/identitee/identifiables.rb', line 20

def find key, *default_values, &block
  instances.fetch key.to_s do 
    lazy_load key

    instances.fetch key.to_s do
      if block
        block.call key
      elsif default_values.length > 0
        default_values.first
      else
        raise ::Identitee::IdentifiableNotFound
      end
    end
  end
end

#find_key(instance) ⇒ Object



36
37
38
# File 'lib/identitee/identifiables.rb', line 36

def find_key instance
  instances.invert.fetch(instance, nil)
end

#lazy_load(key) ⇒ Object



45
46
47
# File 'lib/identitee/identifiables.rb', line 45

def lazy_load key
  (loaders.detect { |loader| loader.loadable? key } || EmptyLoader.new).lazy_load key
end

#register(key, instance) ⇒ Object



16
17
18
# File 'lib/identitee/identifiables.rb', line 16

def register key, instance
  instances[key.to_s] = instance
end