Sha256: 97544642410aa4f3ad1aa816791e4249ccf53993c3cde8ce7b06bf97f5ebe64f

Contents?: true

Size: 1.14 KB

Versions: 8

Compression:

Stored size: 1.14 KB

Contents

# frozen_string_literal: true

require "action_view"

module CableReady
  module Identifiable
    def dom_id(record, prefix = nil)
      return record.to_dom_selector if record.respond_to?(:to_dom_selector)

      prefix = prefix.to_s.strip if prefix

      id = if record.respond_to?(:to_dom_id)
        record.to_dom_id
      elsif ar_relation?(record)
        [prefix, record.model_name.plural].compact.join("_")
      elsif ar_base?(record)
        ActionView::RecordIdentifier.dom_id(record, prefix)
      else
        [prefix, record.to_s.strip].compact.join("_")
      end

      "##{id}".squeeze("#").strip.downcase
    end

    def identifiable?(obj)
      (
        obj.respond_to?(:to_dom_selector) ||
        obj.respond_to?(:to_dom_id) ||
        ar_relation?(obj) ||
        ar_base?(obj)
      )
    end

    private

    def ar_relation?(obj)
      return false if defined?(ActiveRecord).nil? || defined?(ActiveRecord::Relation).nil?

      obj.is_a?(ActiveRecord::Relation)
    end

    def ar_base?(obj)
      return false if defined?(ActiveRecord).nil? || defined?(ActiveRecord::Base).nil?

      obj.is_a?(ActiveRecord::Base)
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
cable_ready-5.0.6 lib/cable_ready/identifiable.rb
cable_ready-5.0.3 lib/cable_ready/identifiable.rb
cable_ready-5.0.2 lib/cable_ready/identifiable.rb
cable_ready-5.0.1 lib/cable_ready/identifiable.rb
cable_ready-5.0.0 lib/cable_ready/identifiable.rb
cable_ready-5.0.0.rc2 lib/cable_ready/identifiable.rb
cable_ready-5.0.0.rc1 lib/cable_ready/identifiable.rb
cable_ready-5.0.0.pre10 lib/cable_ready/identifiable.rb