Class: Positioning::AdvisoryLock

Inherits:
Object
  • Object
show all
Defined in:
lib/positioning/advisory_lock.rb

Defined Under Namespace

Classes: Adapter

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_class, column) ⇒ AdvisoryLock

Returns a new instance of AdvisoryLock.



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
41
42
43
# File 'lib/positioning/advisory_lock.rb', line 10

def initialize(base_class, column)
  @base_class = base_class
  @column = column.to_s

  @adapters = {
    "mysql2" => Adapter.new(
      initialise: -> {},
      aquire: -> { connection.execute "SELECT GET_LOCK(#{connection.quote(lock_name)}, -1)" },
      release: -> { connection.execute "SELECT RELEASE_LOCK(#{connection.quote(lock_name)})" }
    ),
    "postgresql" => Adapter.new(
      initialise: -> {},
      aquire: -> { connection.execute "SELECT pg_advisory_lock(#{lock_name.hex & 0x7FFFFFFFFFFFFFFF})" },
      release: -> { connection.execute "SELECT pg_advisory_unlock(#{lock_name.hex & 0x7FFFFFFFFFFFFFFF})" }
    ),
    "sqlite3" => Adapter.new(
      initialise: -> {
        FileUtils.mkdir_p "#{Dir.pwd}/tmp"
        filename = "#{Dir.pwd}/tmp/#{lock_name}.lock"
        @file ||= File.open filename, File::RDWR | File::CREAT, 0o644
      },
      aquire: -> {
        @file.flock File::LOCK_EX
      },
      release: -> {
        @file.flock File::LOCK_UN
      }
    )
  }

  @adapters.default = Adapter.new(initialise: -> {}, aquire: -> {}, release: -> {})

  adapter.initialise.call
end

Instance Attribute Details

#base_classObject (readonly)

Returns the value of attribute base_class.



8
9
10
# File 'lib/positioning/advisory_lock.rb', line 8

def base_class
  @base_class
end

Instance Method Details

#aquire(record) ⇒ Object Also known as: before_create, before_update, before_destroy



45
46
47
# File 'lib/positioning/advisory_lock.rb', line 45

def aquire(record)
  adapter.aquire.call
end

#release(record) ⇒ Object Also known as: after_commit, after_rollback



49
50
51
# File 'lib/positioning/advisory_lock.rb', line 49

def release(record)
  adapter.release.call
end