Class: Moneta::Adapters::ActiveRecord

Inherits:
Object
  • Object
show all
Includes:
Defaults
Defined in:
lib/moneta/adapters/active_record.rb

Instance Method Summary collapse

Methods included from Defaults

#[]=, #fetch

Constructor Details

#initialize(options = {}) ⇒ ActiveRecord

Returns a new instance of ActiveRecord.



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/moneta/adapters/active_record.rb', line 14

def initialize(options = {})
  @options = options
  unless self.class.const_defined?('Store')
    self.class.const_set('Store', Class.new(::ActiveRecord::Base)) # this prevents loading issues when active_record gem is unavailable
    Store.set_table_name(@options[:table] || 'moneta_store')
  end

  if @options[:connection]
    Store.establish_connection @options[:connection]
  end
end

Instance Method Details

#[](key) ⇒ Object



40
41
42
43
# File 'lib/moneta/adapters/active_record.rb', line 40

def [](key)
  record = Store.find_by_key key_for(key)
  record ? deserialize(record.value) : nil
end

#clearObject



61
62
63
# File 'lib/moneta/adapters/active_record.rb', line 61

def clear
  Store.delete_all
end

#delete(key) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/moneta/adapters/active_record.rb', line 45

def delete(key)
  record = Store.find_by_key key_for(key)
  if record
    Store.where(:key => key_for(record.key)).delete_all
    deserialize record.value
  end
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
38
# File 'lib/moneta/adapters/active_record.rb', line 35

def key?(key)
  record = Store.find_by_key key_for(key)
  !record.nil?
end

#migrateObject



26
27
28
29
30
31
32
33
# File 'lib/moneta/adapters/active_record.rb', line 26

def migrate
  unless Store.table_exists?
    Store.connection.create_table Store.table_name do |t|
      t.string   'key', :primary => :true
      t.string   'value'
    end
  end
end

#store(key, value, options = {}) ⇒ Object



53
54
55
56
57
58
59
# File 'lib/moneta/adapters/active_record.rb', line 53

def store(key, value, options = {})
  record = Store.find_by_key key_for(key)
  record ||= Store.new :key => key_for(key)
  record.value = serialize(value)
  record.save!
  value
end