Sha256: c6f37974cbf30f5215ab75b8b4472c7dc509a7aeb7cd94854d1d59560281735e

Contents?: true

Size: 1.77 KB

Versions: 1

Compression:

Stored size: 1.77 KB

Contents

# frozen_string_literal: true

# == Schema Information
#
# Table name: content_storages
#
#  id                   :integer          not null, primary key
#  title_translations   :hstore           default({})
#  content_translations :hstore           default({})
#  params               :hstore           default({})
#  key                  :string(100)      not null
#  cacheable            :boolean          default(FALSE)
#  type_id              :integer          not null
#  created_at           :datetime         not null
#  updated_at           :datetime         not null
#

class ContentStorage < ActiveRecord::Base
  include TranslationCms::WhiteList
  before_validation :apply_empty_key

  translates :title, :content
  enumerated_attribute :type, class_name: ContentStorageType
  white_list :content

  validates :key, presence: true, uniqueness: true, length: { maximum: 100 }

  class << self
    def get(key)
      return if key.blank?

      find_by(key: key)
    end
  end

  def type_title
    return if type.blank?

    type.title
  end

  def content!
    return content unless persisted?

    Rails.cache.fetch "content_storage_#{key}_#{I18n.locale}", expires_in: 4.hours do
      content
    end
  end

  protected

  def apply_empty_key
    self.key ||= type.code if type.present?
  end

  def method_missing_with_param_fallback(method, *args, &block)
    matched = /^param_([a-zA-Z0-9_]{1,50})(=)?$/.match(method.to_s)
    if matched
      key, operator = matched.captures
      case operator
      when '=' then params[key]
      when nil then params[key] = args.first
      else method_missing_without_param_fallback method, *args, &block
      end
    else method_missing_without_param_fallback method, *args, &block
    end
  end
  alias_method_chain :method_missing, :param_fallback
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
translation_cms-0.1.5 app/models/content_storage.rb