Module: NamedInstances::ClassMethods

Defined in:
lib/named_instances.rb

Instance Method Summary collapse

Instance Method Details

#get(*names) ⇒ Object

Raises:

  • (ArgumentError)


28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/named_instances.rb', line 28

def get *names
  load_named_instances unless @named_instances_loaded

  name = names.map {|n| n.to_s }.join "_"
  key_name = "#{named_instances_prefix}_#{name}"
  result = Rails.cache.read(key_name)

  # gets are hard-coded and should always return something valid from the cache
  raise(ArgumentError, "NamedInstance does not exist: #{key_name}") unless result

  result
end

#has_named_instances(name_method = :value, options = {}) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/named_instances.rb', line 9

def has_named_instances(name_method = :value, options={})
  @named_instances_loaded = false
  @named_instances_name_method = name_method
  @find_options = options[:find_options]

  after_save do
    Rails.logger.info("Reloading #{self} named instances because of a save")
    self.load_named_instances
  end
end

#load_named_instancesObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/named_instances.rb', line 49

def load_named_instances
  begin
    all(@find_options).each do |instance|
      if (@named_instances_name_method.is_a? String) or (@named_instances_name_method.is_a? Symbol)
        field_name = named_instances_normalize instance.send(@named_instances_name_method)
        key_name = "#{named_instances_prefix}_#{field_name}"
      else
        key_name = @named_instances_name_method.inject(named_instances_prefix) do |key_name, name_method|
          field_name = named_instances_normalize instance.send(name_method)
          key_name + "_#{field_name}"
        end
      end

      Rails.cache.write(key_name, instance)
    end

    @named_instances_loaded = true
  rescue Exception => e
    Rails.logger.info "Named Instances: exception ignored, class = #{self}, error = #{e.inspect}"
  end
end

#name_methodObject



24
25
26
# File 'lib/named_instances.rb', line 24

def name_method
  @named_instances_name_method
end

#named_instances_loaded?Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/named_instances.rb', line 20

def named_instances_loaded?
  !! @named_instances_loaded
end

#named_instances_normalize(name) ⇒ Object



41
42
43
# File 'lib/named_instances.rb', line 41

def named_instances_normalize name
  name.downcase.gsub(/[^a-z0-9]+/, '_').gsub(/_$/, '')
end

#named_instances_prefixObject



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

def named_instances_prefix
  "named_instances_#{self}"
end