Module: Voltron::Encryptable::InstanceMethods

Defined in:
lib/voltron/encryptable.rb

Instance Method Summary collapse

Instance Method Details

#find_idObject



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/voltron/encryptable.rb', line 67

def find_id
  # Helps determine the min/max value. For example if amount is 1100, min will be 1024, if amount is 947, min will be 1
  amount = Voltron::Id.count.to_f

  # The range of ids from which we try to find an unused id, i.e. - (1..1024), (1025..2048), (2049..3073)
  factor = 1024.to_f

  # Get the min and max value of the range segment
  min = (((amount/factor).floor*factor) + 1).to_i
  max = (((amount+1)/factor).ceil*factor).to_i

  # Get all ids in the determined range segment, these are the ids we cannot choose from
  used = Voltron::Id.where(id: min..max).pluck(:id)
  # Get the candidates, an array of values from min to max, subtracting the used values from above
  candidates = ((min..max).to_a - used).shuffle
  # Get the first candidate, the first value off the shuffled array
  candidate = candidates.shift

  # Check for blacklisted words given the candidate id
  while crypt.blacklisted?(candidate) do
    # If id chosen is a blacklisted word, insert it as a placeholder record and try again
    Voltron::Id.create(id: candidate, resource_id: 0, resource_type: :blacklist)

    # If no more candidates to choose from, re-run find_id, it will get a new set of candidates from the next segment
    return find_id if candidates.empty?

    # Pick the next candidate
    candidate = candidates.shift
  end

  # The id chosen is good, not a blacklisted word. Use it
  candidate
end

#reload(options = nil) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/voltron/encryptable.rb', line 101

def reload(options = nil)
  clear_aggregation_cache
  clear_association_cache
  self.class.connection.clear_query_cache

  fresh_object =
    if options && options[:lock]
      self.class.unscoped { self.class.lock(options[:lock]).find_by(id: encryptable.resource_id) }
    else
      self.class.unscoped { self.class.find(encryptable.resource_id, bypass: true) }
    end

  @attributes = fresh_object.instance_variable_get("@attributes")
  @new_record = false
  self
end

#to_paramObject



60
61
62
63
64
65
# File 'lib/voltron/encryptable.rb', line 60

def to_param
  return super if encryptable.nil?

  crypt = Voltron::Encrypt.new
  crypt.encode(encryptable.id)
end