Module: Hashid::Rails::ClassMethods

Defined in:
lib/hashid/rails.rb

Instance Method Summary collapse

Instance Method Details

#decode_id(ids, fallback: false) ⇒ Object

Parameters:

  • ids (String, Integer, Array<Integer, String>)

    id(s) to decode.

  • fallback (Boolean) (defaults to: false)

    indicates whether to return the passed in id(s) if unable to decode or if already decoded.



60
61
62
63
64
65
66
# File 'lib/hashid/rails.rb', line 60

def decode_id(ids, fallback: false)
  if ids.is_a?(Array)
    ids.map { |id| hashid_decode(id, fallback: fallback) }
  else
    hashid_decode(ids, fallback: fallback)
  end
end

#encode_id(ids) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/hashid/rails.rb', line 49

def encode_id(ids)
  if ids.is_a?(Array)
    ids.map { |id| hashid_encode(id) }
  else
    hashid_encode(ids)
  end
end

#find(*ids) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/hashid/rails.rb', line 68

def find(*ids)
  expects_array = ids.first.is_a?(Array)

  uniq_ids = ids.flatten.compact.uniq
  uniq_ids = uniq_ids.first unless expects_array || uniq_ids.size > 1

  if Hashid::Rails.configuration.override_find
    super(decode_id(uniq_ids, fallback: true))
  else
    super
  end
end

#find_by_hashid(hashid) ⇒ Object



81
82
83
# File 'lib/hashid/rails.rb', line 81

def find_by_hashid(hashid)
  find_by(id: decode_id(hashid, fallback: false))
end

#find_by_hashid!(hashid) ⇒ Object



85
86
87
# File 'lib/hashid/rails.rb', line 85

def find_by_hashid!(hashid)
  find_by!(id: decode_id(hashid, fallback: false))
end

#has_many(*args, &block) ⇒ Object



43
44
45
46
47
# File 'lib/hashid/rails.rb', line 43

def has_many(*args, &block)
  options = args.extract_options!
  options[:extend] = Array(options[:extend]).push(ClassMethods)
  super(*args, options, &block)
end

#relationObject



39
40
41
# File 'lib/hashid/rails.rb', line 39

def relation
  super.tap { |r| r.extend ClassMethods }
end