static_model.rb 847 Bytes
Newer Older
1 2
# frozen_string_literal: true

3 4 5 6
# Provides an ActiveRecord-like interface to a model whose data is not persisted to a database.
module StaticModel
  extend ActiveSupport::Concern

7
  class_methods do
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
    # Used by ActiveRecord's polymorphic association to set object_id
    def primary_key
      'id'
    end

    # Used by ActiveRecord's polymorphic association to set object_type
    def base_class
      self
    end
  end

  # Used by AR for fetching attributes
  #
  # Pass it along if we respond to it.
  def [](key)
23
    send(key) if respond_to?(key) # rubocop:disable GitlabSecurity/PublicSend
24 25 26 27 28 29
  end

  def to_param
    id
  end

30 31 32 33
  def new_record?
    false
  end

34 35 36 37 38 39 40
  def persisted?
    false
  end

  def destroyed?
    false
  end
41 42

  def ==(other)
43
    if other.is_a? ::StaticModel
44 45 46 47 48
      id == other.id
    else
      super
    end
  end
49
end