Sha256: 7ced3509ea2f76b6456b5f1bb1956834dae234523d357ae5c42bf2a9b583eb5a

Contents?: true

Size: 1.72 KB

Versions: 3

Compression:

Stored size: 1.72 KB

Contents

# frozen_string_literal: true

# ObjectIdentifier::Parameters encapsulates the attributes list and
# formatter options that may be needed for custom formatting during object
# identification.
class ObjectIdentifier::Parameters
  # This String to display if `formatter_options[:klass]` isn't present.
  KLASS_NOT_GIVEN = "NOT_GIVEN"

  attr_reader :attributes

  # Factory method for building an {ObjectIdentifier::Parameters} object. Uses
  # ObjectIdentifier.default_attributes if the given `attributes` array is
  # empty.
  def self.build(attributes: [], formatter_options: {})
    attrs = ObjectIdentifier::ArrayWrap.(attributes)
    attrs = ObjectIdentifier.default_attributes if attrs.empty?
    attrs.flatten!

    new(
      attributes: attrs,
      formatter_options: formatter_options.to_h)
  end

  # @param attributes [Array, *args] A list of method calls to interrogate the
  #   given object(s) with.
  # @option formatter_options[:limit] [Integer, nil] A given limit on the number
  #   of objects to interrogate.
  # @option formatter_options[:klass] [#to_s] A preferred type name for
  #   identifying the given object(s) as.
  def initialize(
        attributes: [],
        formatter_options: {})
    @attributes = attributes
    @limit = formatter_options.fetch(:limit, nil)
    @klass = formatter_options.fetch(:klass, KLASS_NOT_GIVEN)
  end

  # NOTE: Expects a block if a value wasn't supplied on initialization.
  def limit
    @limit || (yield if block_given?)
  end

  # NOTE: Expects a block if a value wasn't supplied on initialization.
  def klass
    if klass_given?
      @klass.to_s
    elsif block_given?
      yield.to_s
    else
      nil
    end
  end

  private

  def klass_given?
    @klass != KLASS_NOT_GIVEN
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
object_identifier-0.9.0 lib/object_identifier/parameters.rb
object_identifier-0.8.0 lib/object_identifier/parameters.rb
object_identifier-0.7.0 lib/object_identifier/parameters.rb