about summary refs log tree commit diff
path: root/app/models/account_metadata.rb
blob: bb0f7676edaf87f7a76fb60a5b8b7a2025c7f732 (plain) (blame)
1
2
3
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
52
# frozen_string_literal: true
# == Schema Information
#
# Table name: account_metadata
#
#  id         :bigint(8)        not null, primary key
#  account_id :bigint(8)        not null
#  fields     :jsonb            not null
#

class AccountMetadata < ApplicationRecord
  include Cacheable

  belongs_to :account, inverse_of: :metadata
  cache_associated :account

  def fields
    self[:fields].presence || {}
  end

  def fields_json
    fields.select { |name, _| name.start_with?('custom:') }
          .map do |name, value|
            {
              '@context': {
                schema: 'http://schema.org/',
                name: 'schema:name',
                value: 'schema:value',
              },
              type: 'PropertyValue',
              name: name,
              value: value.is_a?(Array) ? value.join("\r\n") : value,
            }
          end
  end

  def cached_fields_json
    Rails.cache.fetch("custom_metadata:#{account_id}", expires_in: 1.hour) do
      fields_json
    end
  end

  class << self
    def create_or_update(fields)
      create(fields).presence || update(fields)
    end

    def create_or_update!(fields)
      create(fields).presence || update!(fields)
    end
  end
end