Sha256: bfc5083d78c3a294454df35da41930565f448f235ed805ffeeddcea98d6f0b4d

Contents?: true

Size: 1.81 KB

Versions: 2

Compression:

Stored size: 1.81 KB

Contents

require 'rack/session/abstract/id'
require 'active_support/cache'

module Telegram
  module Bot
    class UpdatesController
      # Add functionality to store data between requests.
      module Session
        extend ActiveSupport::Concern

        def process_action(*)
          super
        ensure
          session.commit
        end

        protected

        def session
          @_session ||= SessionHash.new(self.class.session_store, session_key)
        end

        def session_key
          "#{bot.username}:#{from ? "from:#{from['id']}" : "chat:#{chat['id']}"}"
        end

        # Rack::Session::Abstract::SessionHash is taken to provide lazy loading.
        # All methods that access store are overriden to support
        # ActiveSupport::Cache::Store stores.
        class SessionHash < Rack::Session::Abstract::SessionHash
          attr_reader :id

          def initialize(store, id)
            @store = store
            @id = id
          end

          def destroy
            clear
            @store.delete(id)
          end

          def exists?
            return @exists if defined?(@exists)
            @data = {}
            @exists = @store.exist? id
          end

          def load!
            session = @store.read(id)
            @data = session ? stringify_keys(session) : {}
            @loaded = true
          end

          def commit
            return unless loaded?
            data = to_hash.delete_if { |_, v| v.nil? }
            @store.write(id, data)
          end
        end

        module ConfigMethods
          delegate :session_store, to: :config

          def session_store=(store)
            config.session_store = ActiveSupport::Cache.lookup_store(store)
          end

          def use_session!
            include Session
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
telegram-bot-0.6.0 lib/telegram/bot/updates_controller/session.rb
telegram-bot-0.5.0 lib/telegram/bot/updates_controller/session.rb