Sha256: e8db89aba8b87344dc967976767077dfb7baca826abb279ddb11a08586cd7e0e

Contents?: true

Size: 1.99 KB

Versions: 1

Compression:

Stored size: 1.99 KB

Contents

require 'rubygems'
require 'action_controller'


class NoCountdown < Exception; end

module SessionCountdown

  @@default_name = "default"

  def countdown_run(delta, name = @@default_name)
    self[get_zero_key(name)] = Time.now + delta
    self[get_zero_delta_key(name)] = delta # save for reset
  end

  def countdown_running?(name = @@default_name)
    self[get_zero_key(name)] && self[get_zero_key(name)] > Time.now
  end

  def countdown_expired?(name = @@default_name)
    self[get_zero_key(name)] && ! countdown_running?(name)
  end

  # sanity checkpoint for some methods, checking for existing countdown
  def method_missing(method, *args)

    method = "_#{method}" # super secret shadow method

    # first check if method exists
    raise NoMethodError unless respond_to?(method)

    # check if specified countdown timer exists - reason for this method_missing
    insist_countdown_exists(*args)

    # finally run method
    send(method, *args)

  end

  ## these methods all require a sanity check for existing countdown

  def _countdown_expire(name = @@default_name)
    self[get_zero_key(name)] = Time.now
  end

  def _countdown_restart(name = @@default_name)
    self[get_zero_key(name)] = Time.now + self[get_zero_delta_key(name)]
  end

  def _countdown_count(name = @@default_name)
    remaining = (self[get_zero_key(name)] - Time.now)
    (remaining > 0) ? remaining : 0
  end


  private #~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*


  def get_zero_key(name)
    "session_countdown:#{name}"
  end

  def get_zero_delta_key(name)
    "session_countdown:#{name}_delta"
  end

  def insist_countdown_exists(name = @@default_name)
    unless self[get_zero_key(name)]
      raise NoCountdown, "no session countdown named '#{name}'"
    end
  end

end


if Rails::VERSION::MAJOR == 2

  class ActionController::Session::AbstractStore::SessionHash
    include SessionCountdown
  end

else

  class ActionDispatch::Session::AbstractStore::SessionHash
    include SessionCountdown
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
session_countdown-0.3.0 lib/session_countdown.rb