Skip to content

Instantly share code, notes, and snippets.

@epintos
Last active January 18, 2016 17:39
Show Gist options
  • Save epintos/d2ca0c63d1be5eca1d1e to your computer and use it in GitHub Desktop.
Save epintos/d2ca0c63d1be5eca1d1e to your computer and use it in GitHub Desktop.
UniqueTokenValidator Concern
module UniqueTokenValidator
extend ActiveSupport::Concern
included do
validates :unique_token, uniqueness: true, allow_nil: true
before_validation :generate_unique_token
end
def generate_unique_token
if !self.class::UNIQUE_FIELDS[:condition].present? ||
self.class::UNIQUE_FIELDS[:condition].call(self)
self.unique_token = Digest::SHA1.hexdigest(
self.class::UNIQUE_FIELDS.except(:condition).values.flatten.map { |k| send(k).to_s }.join
)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment