Class: RunOnce
- Inherits:
-
Object
- Object
- RunOnce
- Defined in:
- lib/run_once.rb
Class Attribute Summary collapse
-
.db_file ⇒ Object
Returns the value of attribute db_file.
Class Method Summary collapse
- .get_a_context ⇒ Object
- .in(seconds, &bl) ⇒ Object
- .lookup_db(key) ⇒ Object
- .update_db(key, val) ⇒ Object
- .use_file=(file) ⇒ Object
- .use_path=(path) ⇒ Object
- .with_context(context) ⇒ Object
Instance Method Summary collapse
- #in(seconds) ⇒ Object
-
#initialize(context) ⇒ RunOnce
constructor
A new instance of RunOnce.
- #last_happened ⇒ Object
- #update_last_happened ⇒ Object
Constructor Details
#initialize(context) ⇒ RunOnce
Returns a new instance of RunOnce.
63 64 65 |
# File 'lib/run_once.rb', line 63 def initialize(context) @context = context end |
Class Attribute Details
.db_file ⇒ Object
Returns the value of attribute db_file.
4 5 6 |
# File 'lib/run_once.rb', line 4 def db_file @db_file end |
Class Method Details
.get_a_context ⇒ Object
15 16 17 |
# File 'lib/run_once.rb', line 15 def get_a_context self.new(caller[1]) end |
.in(seconds, &bl) ⇒ Object
23 24 25 |
# File 'lib/run_once.rb', line 23 def in(seconds, &bl) get_a_context.in(seconds, &bl) end |
.lookup_db(key) ⇒ Object
37 38 39 40 41 42 43 44 |
# File 'lib/run_once.rb', line 37 def lookup_db(key) retval = nil File.open(@db_file, 'r') do |io| io.flock(File::LOCK_SH) retval = io.readline.strip if search_db(io,key) end retval end |
.update_db(key, val) ⇒ Object
27 28 29 30 31 32 33 34 35 |
# File 'lib/run_once.rb', line 27 def update_db(key, val) formatted_val = '%015.3f' % val.to_f File.open(@db_file, 'w+') do |io| io.flock(File::LOCK_EX) io.rewind io.puts key if !search_db(io,key) io.puts formatted_val end end |
.use_file=(file) ⇒ Object
10 11 12 13 |
# File 'lib/run_once.rb', line 10 def use_file=(file) self.db_file = file File.open(@db_file, 'a+') { } end |
.use_path=(path) ⇒ Object
6 7 8 |
# File 'lib/run_once.rb', line 6 def use_path=(path) self.use_file = path + "/#{self}.db.#{$$}" end |
.with_context(context) ⇒ Object
19 20 21 |
# File 'lib/run_once.rb', line 19 def with_context(context) new(context) end |
Instance Method Details
#in(seconds) ⇒ Object
67 68 69 70 71 72 |
# File 'lib/run_once.rb', line 67 def in(seconds) if(!last_happened || last_happened && (Time.now.to_f > (last_happened + seconds.to_f))) update_last_happened yield end end |
#last_happened ⇒ Object
74 75 76 |
# File 'lib/run_once.rb', line 74 def last_happened @last_happened ||= (self.class.lookup_db(@context).to_f rescue nil) end |
#update_last_happened ⇒ Object
78 79 80 |
# File 'lib/run_once.rb', line 78 def update_last_happened self.class.update_db(@context, Time.now.to_f) end |