Class: Glib::Text

Inherits:
DynamicTextRecord show all
Defined in:
app/models/glib/text.rb

Class Method Summary collapse

Class Method Details

.dt_has_many_attached(name, dependent: :purge_later) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'app/models/glib/text.rb', line 4

def dt_has_many_attached(name, dependent: :purge_later)
  generated_association_methods.class_eval <<-CODE, __FILE__, __LINE__ + 1
    def #{name}
      @active_storage_attached_#{name} ||= ::ActiveStorage::Attached::Many.new("#{name}", self)
    end

    def #{name}=(attachables)
      if ActiveStorage.replace_on_assign_to_many
        attachment_changes["#{name}"] =
          if Array(attachables).none?
            ::ActiveStorage::Attached::Changes::DeleteMany.new("#{name}", self)
          else
            ::ActiveStorage::Attached::Changes::CreateMany.new("#{name}", self, attachables)
          end
      else
        if Array(attachables).any?
          attachment_changes["#{name}"] =
            ::ActiveStorage::Attached::Changes::CreateMany.new("#{name}", self, #{name}.blobs + attachables)
        end
      end
    end
  CODE

  has_many :"#{name}_attachments", -> { where(name: name) }, as: :record, class_name: "Glib::ActiveStorage::Attachment", inverse_of: :record, dependent: :destroy do
    def purge
      each(&:purge)
      reset
    end

    def purge_later
      each(&:purge_later)
      reset
    end
  end
  has_many :"#{name}_blobs", through: :"#{name}_attachments", class_name: "Glib::ActiveStorage::Blob", source: :blob

  scope :"with_attached_#{name}", -> { includes("#{name}_attachments": :blob) }

  after_save { attachment_changes[name.to_s]&.save }

  after_commit(on: %i[ create update ]) { attachment_changes.delete(name.to_s).try(:upload) }

  ActiveRecord::Reflection.add_attachment_reflection(
    self,
    name,
    ActiveRecord::Reflection.create(:has_many_attached, name, nil, { dependent: dependent }, self)
  )
end

.get_content(key, default_value, options:) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'app/models/glib/text.rb', line 67

def self.get_content(key, default_value, options:)
  scope_key = "#{options[:scope]}.#{options[:lang]}.#{key}"

  content = redis.get(scope_key)
  text = find_by(scope: options[:scope], lang: options[:lang], key: key)

  if !(content && text)
    if text = find_by(scope: options[:scope], lang: options[:lang], key: key)
      update_content(scope_key, text.content)
      content = text.content
    else
      text = create(scope: options[:scope], lang: options[:lang], key: key, content: default_value)
      update_content(scope_key, default_value)
      content = default_value
    end
  end

  [content, text]
end

.redisObject



63
64
65
# File 'app/models/glib/text.rb', line 63

def self.redis
  Glib::DynamicText::Config.redis
end