module TokenSegment::ClassMethods

Public Instance Methods

has_token(attribute, options={}, &block) click to toggle source
# File lib/user_plane/token_segment.rb, line 8
def has_token(attribute, options={}, &block)
  # Generates a random token on a given attirubte at creation time.
  # optionally it can create it for every update of the record.

  validates attribute, uniqueness: true

  if life_span = options[:expires_in]
    scope :stale, -> {unscoped.where('created_at <= ?', life_span.ago)}
    scope :fresh, -> {where('created_at > ?', life_span.ago)}

    define_method :stale? do
      if new_record?
        false
      else
        created_at <= life_span.ago
      end
    end
  end

  define_method :"regenerate_#{attribute}" do
    if block_given?
      make_token attribute, instance_eval(&block)
    else
      make_token attribute
    end
  end  

  if regenerate_on = options[:regenerate_on]
    before_validation :"regenerate_#{attribute}", on: regenerate_on
  else
    before_validation :"regenerate_#{attribute}" 
  end
end