module ActsAsHashids::Core::FinderMethods

Public Instance Methods

find(ids = nil, &block) click to toggle source
# File lib/acts_as_hashids/core.rb, line 13
def find(ids = nil, &block)
  return detect(&block) if block.present? && respond_to?(:detect)

  encoded_ids = Array(ids).map do |id|
    id = id.to_i if Integer(id)
    hashids.encode(id)
  rescue TypeError, ArgumentError
    id
  end

  encoded_ids = encoded_ids.flatten

  res = with_hashids(encoded_ids).all
  if ids.is_a?(Array)
    raise_record_not_found_exception! encoded_ids, res.size, encoded_ids.size if res.size != encoded_ids.size
  else
    raise_record_not_found_exception! encoded_ids[0], res.size, encoded_ids.size if res.empty?
    res = res[0]
  end
  res
end

Private Instance Methods

raise_record_not_found_exception!(ids, result_size, expected_size) click to toggle source
# File lib/acts_as_hashids/core.rb, line 37
def raise_record_not_found_exception!(ids, result_size, expected_size)
  if Array(ids).size == 1
    error = "Couldn't find #{name} with '#{primary_key}'=#{ids.inspect}"
  else
    error = "Couldn't find all #{name.pluralize} with '#{primary_key}': "
    error << "(#{ids.map(&:inspect).join(', ')}) (found #{result_size} results, but was looking for #{expected_size})"
  end

  raise ActiveRecord::RecordNotFound, error
end