Class: Hedgerow
- Inherits:
-
Object
- Object
- Hedgerow
- Defined in:
- lib/hedgerow.rb,
lib/hedgerow/version.rb
Defined Under Namespace
Classes: LockFailure
Constant Summary collapse
- VERSION =
"0.1.4"
Class Method Summary collapse
- .connection ⇒ Object
- .connection=(connection) ⇒ Object
- .lock(name, timeout) ⇒ Object
- .parse_response(r) ⇒ Object
- .release(name) ⇒ Object
- .validate_name!(name) ⇒ Object
- .with(name, opts = {}) ⇒ Object
Class Method Details
.connection ⇒ Object
40 41 42 43 44 45 46 47 48 |
# File 'lib/hedgerow.rb', line 40 def connection @@connection ||= begin if defined?(ActiveRecord) ActiveRecord::Base.connection.raw_connection else raise "Could not find connection for hedgerow." end end end |
.connection=(connection) ⇒ Object
36 37 38 |
# File 'lib/hedgerow.rb', line 36 def connection=(connection) @@connection = connection end |
.lock(name, timeout) ⇒ Object
15 16 17 18 |
# File 'lib/hedgerow.rb', line 15 def lock(name, timeout) validate_name!(name) parse_response connection.prepare("SELECT GET_LOCK(?, ?)").execute(name, timeout) end |
.parse_response(r) ⇒ Object
31 32 33 34 |
# File 'lib/hedgerow.rb', line 31 def parse_response(r) val = r.to_a.flatten.first rescue 0 val == 1 ? true : false end |
.release(name) ⇒ Object
20 21 22 23 |
# File 'lib/hedgerow.rb', line 20 def release(name) validate_name!(name) parse_response connection.prepare("SELECT RELEASE_LOCK(?)").execute(name) end |
.validate_name!(name) ⇒ Object
25 26 27 28 29 |
# File 'lib/hedgerow.rb', line 25 def validate_name!(name) if name.length > 64 raise LockFailure.new("MySQL enforces a maximum length on lock names of 64 characters.") end end |
.with(name, opts = {}) ⇒ Object
5 6 7 8 9 10 11 12 13 |
# File 'lib/hedgerow.rb', line 5 def with(name, opts = {}) if status = lock(name, opts[:timeout] || 10) yield else raise LockFailure.new("Could not acquire lock.") end ensure release(name) if status end |