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.



80
81
82
83
84
85
86
# File 'lib/hashid/rails.rb', line 80

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



69
70
71
72
73
74
75
# File 'lib/hashid/rails.rb', line 69

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

#find(*ids) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/hashid/rails.rb', line 88

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_configuration.override_find
    super(decode_id(uniq_ids, fallback: true))
  else
    super
  end
end

#find_by_hashid(hashid) ⇒ Object



101
102
103
# File 'lib/hashid/rails.rb', line 101

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

#find_by_hashid!(hashid) ⇒ Object



105
106
107
# File 'lib/hashid/rails.rb', line 105

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

#has_many(*args, &block) ⇒ Object



63
64
65
66
67
# File 'lib/hashid/rails.rb', line 63

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

#hashid_config(options = {}) ⇒ Object



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

def hashid_config(options = {})
  config = Hashid::Rails.configuration.dup
  config.pepper = table_name
  options.each do |attr, value|
    config.public_send("#{attr}=", value)
  end
  @hashid_configuration = config
end

#hashid_configurationObject



51
52
53
# File 'lib/hashid/rails.rb', line 51

def hashid_configuration
  @hashid_configuration || hashid_config
end

#relationObject



59
60
61
# File 'lib/hashid/rails.rb', line 59

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

#reset_hashid_configObject



55
56
57
# File 'lib/hashid/rails.rb', line 55

def reset_hashid_config
  @hashid_configuration = nil
end