Sha256: 06fe5688a7bd734627a1372f5013f5c8011eada35162a7d149ea0cb33ba04f3b

Contents?: true

Size: 934 Bytes

Versions: 1

Compression:

Stored size: 934 Bytes

Contents

# frozen_string_literal: true

require_relative "inspectacular/version"

# Extend any object to get a custom #inspect method with the given attributes. If no attributes are
# given, the default is to inspect the object's #id attribute.
#
# Example:
#
#   class User < ApplicationRecord
#     extend Inspector[:id, :name, :email]
#   end
#
#   User.first.inspect
#   #=> "#<User id: 1, name: 'John Doe', email: 'john@doe.com'>
module Inspectacular
  def self.extended(base) # :nodoc:
    base.class_eval do
      class_attribute :inspected_attrs, instance_predicate: false, default: [:id]

      def inspect
        str = "#<#{self.class.name} "
        attrs = self.class.inspected_attrs.map { |attr| "#{attr}: #{send(attr).inspect}" }
        str << attrs.join(', ') << '>'
      end
    end
    base.inspected_attrs = @inspected_attrs if @inspected_attrs
  end

  def self.[](*attrs)
    @inspected_attrs = attrs
    self
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
inspectacular-1.0.0 lib/inspectacular.rb