# frozen_string_literal: true

class Object
  def subclass_of?(superclass)
    respond_to?(:ancestors) ? ancestors.include?(superclass) : self.class.ancestors.include?(superclass)
  end

  def descendants
    descendants = []
    ObjectSpace.each_object(singleton_class) do |k|
      descendants.unshift k unless k == self
    end
    descendants
  end
end

class String
  def indent(depth = 1, size = 4)
    split("\n", -1).collect { |line| (' ' * size * depth) + line }.join("\n")
  end

  def max_length(length = 25, always_trail: false)
    trail = always_trail ? '...' : ''
    self.length > length ? "#{self[0..(length - 3)]}..." : "#{self}#{trail}"
  end

  def sanitize
    gsub(/[^0-9A-Z]+/i, '-')
  end
end

class Hash
  def except(*keys)
    dup.except!(*keys)
  end

  def except!(*keys)
    keys.each { |key| delete(key) }
    self
  end
end
