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 LINKLIST_NAME = "related_links".freeze # @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 # add method for get related_links attiribute for simply Obj-instance attributes = RailsConnector::Attribute.where(attribute_name: LINKLIST_NAME) if attributes.length != 0 Obj.send(:define_attribute, LINKLIST_NAME, ActiveRecord::Type::String.new) Obj.send(:delegate, LINKLIST_NAME.to_sym, to: :attr_dict) else Rails.logger.warn "Check if you NamedLink class is defined properly. Attibute related_links does not exist." # there is not attribute named 'related_links' defined @@named_links_cache = [] @@updated_at = Time.now return nil end 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 .flat_map(&:related_links) .each_with_object({}) do |link_obj, temp| temp[link_obj.title] = link_obj.destination_object end @@updated_at = Time.now 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}' 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