class FmRest::TokenStore::ActiveRecord

Heavily inspired by Moneta's ActiveRecord store:

https://github.com/minad/moneta/blob/master/lib/moneta/adapters/activerecord.rb

Constants

DEFAULT_TABLE_NAME

Attributes

connection_lock[R]
connection_pool[R]
model[R]

Private Class Methods

new(options = {}) click to toggle source
Calls superclass method
# File lib/fmrest/token_store/active_record.rb, line 24
def initialize(options = {})
  super

  @connection_pool = ::ActiveRecord::Base.connection_pool

  create_table

  @model = Class.new(::ActiveRecord::Base)
  @model.table_name = table_name
end

Private Instance Methods

create_table() click to toggle source
# File lib/fmrest/token_store/active_record.rb, line 52
def create_table
  with_connection do |conn|
    return if conn.table_exists?(table_name)

    # Prevent multiple connections from attempting to create the table simultaneously.
    self.class.connection_lock.synchronize do
      conn.create_table(table_name, id: false) do |t|
        t.string :scope, null: false
        t.string :token, null: false
        t.datetime :updated_at
      end
      conn.add_index(table_name, :scope, unique: true)
      conn.add_index(table_name, [:scope, :token])
    end
  end
end
delete(key) click to toggle source
# File lib/fmrest/token_store/active_record.rb, line 35
def delete(key)
  model.where(scope: key).delete_all
end
load(key) click to toggle source
# File lib/fmrest/token_store/active_record.rb, line 39
def load(key)
  model.where(scope: key).pluck(:token).first
end
store(key, value) click to toggle source
# File lib/fmrest/token_store/active_record.rb, line 43
def store(key, value)
  record = model.find_or_initialize_by(scope: key)
  record.token = value
  record.save!
  value
end
table_name() click to toggle source
# File lib/fmrest/token_store/active_record.rb, line 69
def table_name
  options[:table_name] || DEFAULT_TABLE_NAME
end