module TokenAttr::Concern

Public Instance Methods

generate_tokens() click to toggle source
# File lib/token_attr/concern.rb, line 54
def generate_tokens
  self.class.token_definitions.each do |td|
    if send("should_generate_new_#{td.attr_name}?")
      new_token = nil
      try_count = 0
      begin
        raise TooManyAttemptsError.new(td.attr_name, new_token) if try_count == 5
        new_token = send("generate_new_#{td.attr_name}")
        try_count += 1
      end until token_is_unique?(td, new_token)

      send "#{td.attr_name}=", new_token
    end
  end
end
token_is_unique?(token_definition, token) click to toggle source
# File lib/token_attr/concern.rb, line 70
def token_is_unique?(token_definition, token)
  attr_name  = token_definition.attr_name
  scope_attr = token_definition.scope_attr

  scope = self.class.where(attr_name => token)
  scope = scope.where.not(id: self.id) if self.persisted?
  scope = scope.where(scope_attr => read_attribute(scope_attr)) if scope_attr
  !scope.exists?
end