Module: TokenSegment::ClassMethods

Defined in:
lib/user_plane/token_segment.rb

Instance Method Summary collapse

Instance Method Details

#has_token(attribute, options = {}, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# 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