Skip to content

Instantly share code, notes, and snippets.

@evansharp
Forked from agibralter/random_attribute.rb
Created November 26, 2013 18:04

Revisions

  1. @agibralter agibralter created this gist Sep 25, 2012.
    31 changes: 31 additions & 0 deletions random_attribute.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    module RandomAttribute

    def generate_unique_random_base64(attribute, n)
    until random_is_unique?(attribute)
    self.send(:"#{attribute}=", random_base64(n))
    end
    end

    def generate_unique_random_hex(attribute, n)
    until random_is_unique?(attribute)
    self.send(:"#{attribute}=", SecureRandom.hex(n/2))
    end
    end

    private

    def random_is_unique?(attribute)
    val = self.send(:"#{attribute}")
    val && !self.class.send(:"find_by_#{attribute}", val)
    end

    def random_base64(n)
    val = base64_url
    val += base64_url while val.length < n
    val.slice(0..(n-1))
    end

    def base64_url
    SecureRandom.base64(60).downcase.gsub(/\W/, '')
    end
    end
    11 changes: 11 additions & 0 deletions user.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,11 @@
    class Post < ActiveRecord::Base

    include RandomAttribute
    before_validation :generate_key, on: :create

    private

    def generate_key
    generate_unique_random_hex(:key, 32)
    end
    end