Module: NamedInstances::ClassMethods
- Defined in:
- lib/named_instances/base.rb
Defined Under Namespace
Modules: InstanceMethods
Instance Method Summary collapse
- #get(name_or_names) ⇒ Object
- #get_one(name) ⇒ Object
- #has_named_instances(name_method = :value) ⇒ Object
- #load_named_instances ⇒ Object
- #name_method ⇒ Object
- #named_instances_loaded? ⇒ Boolean
- #named_instances_normalize(name) ⇒ Object
- #named_instances_prefix ⇒ Object
Instance Method Details
#get(name_or_names) ⇒ Object
31 32 33 34 35 36 37 38 39 |
# File 'lib/named_instances/base.rb', line 31 def get name_or_names load_named_instances unless @named_instances_loaded if not name_or_names.is_a?(String) and name_or_names.respond_to? :map name_or_names.map {|name| get_one name } else get_one name_or_names end end |
#get_one(name) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/named_instances/base.rb', line 41 def get_one name return if name.blank? key_name = "#{named_instances_prefix}_#{name}" begin Rails.cache.read key_name rescue load_named_instances Rails.cache.read key_name end end |
#has_named_instances(name_method = :value) ⇒ Object
15 16 17 18 19 20 21 |
# File 'lib/named_instances/base.rb', line 15 def has_named_instances(name_method = :value) @named_instances_loaded = false @named_instances_name_method = name_method after_save {|model| model.class.load_named_instances } include InstanceMethods end |
#load_named_instances ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
# File 'lib/named_instances/base.rb', line 61 def load_named_instances begin all.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_method ⇒ Object
27 28 29 |
# File 'lib/named_instances/base.rb', line 27 def name_method @named_instances_name_method end |
#named_instances_loaded? ⇒ Boolean
23 24 25 |
# File 'lib/named_instances/base.rb', line 23 def named_instances_loaded? !! @named_instances_loaded end |
#named_instances_normalize(name) ⇒ Object
53 54 55 |
# File 'lib/named_instances/base.rb', line 53 def named_instances_normalize name name.downcase.gsub(/[',]/, '').gsub(/[^a-z0-9_]+/, '_').gsub(/_$/, '') end |
#named_instances_prefix ⇒ Object
57 58 59 |
# File 'lib/named_instances/base.rb', line 57 def named_instances_prefix "named_instances_#{self}" end |