module RailsConnector # This class provides methods used to retrieve objects from CMS based an entry # in CMS of the obj_class NamedLink. # @api public class NamedLink # @api public class NotFound < StandardError end @@named_links_cache = nil @@updated_at = nil @@cache_expiry_time = nil # Generates a cache of named links based on the CMS objects related link list. # Raises exceptions if zero or more than one objects have this obj_class def self.generate_named_links_cache return if @@named_links_cache found_objects = BasicObj.where(obj_class: 'NamedLink') Rails.logger.warn "Couldn't find NamedLink CMS Object!" if found_objects.empty? Rails.logger.warn "More than one NamedLink CMS Object found!" if found_objects.size > 1 @@named_links_cache = found_objects. sort_by(&:valid_from). reverse. map(&:related_links). flatten(1). each_with_object({}) do |link_obj, temp| temp[link_obj.title] = link_obj.destination_object end @@updated_at = Time.now return nil end # Sets the time in minutes after which the cache will be expired. # The default expiry time is set to 1 minute # @api public def self.cache_expiry_time=(value) @@cache_expiry_time = value end def self.cache_expiry_time @@cache_expiry_time || 1 end def self.cache_expired? @@updated_at.nil? || @@updated_at <= cache_expiry_time.minute.ago end # Returns the CMS object mapped to the given title or nil. # The title can be a string of symbol. # If :cache => false is provided, the object will not be fetched from the cache. # @api public def self.get_object(title, options = {}) object = named_links[title.to_s] raise NotFound, "The NamedLink '#{title.to_s}' does not exist" if object.nil? options[:cache] == false ? object.reload : object end def self.reset_cache @@named_links_cache = nil end def self.named_links reset_cache if cache_expired? generate_named_links_cache unless named_links_cache named_links_cache end def self.named_links_cache @@named_links_cache end end end