Module: Kernel
- Defined in:
- lib/ext/kernel.rb
Instance Method Summary collapse
-
#each_with_progress(collection) ⇒ Object
Is good for rake tasks, migrations etc.
- #puts_with_time(string) ⇒ Object
-
#track_time {|block| ... } ⇒ Object
returns spent time in milliseconds.
-
#try_to(attempt = 1, &block) ⇒ Object
retrying code ‘attempt’ times with delay ‘attempt’ ** 2.
Instance Method Details
#each_with_progress(collection) ⇒ Object
Is good for rake tasks, migrations etc.
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/ext/kernel.rb', line 26 def each_with_progress(collection) progress = 0 all_count = collection.count puts_with_time "Found before: #{all_count} items." i = 0 collection.find_each(batch_size: 1000) do |item| yield item i = i + 1 current_progress = ((i * 100) / all_count.to_f).floor if current_progress > progress progress = current_progress puts_with_time "Done #{progress}%. #{i} of #{all_count} records." end end puts_with_time "Left after: #{collection.count} items." end |
#puts_with_time(string) ⇒ Object
49 50 51 |
# File 'lib/ext/kernel.rb', line 49 def puts_with_time(string) puts "#{Time.now.utc.strftime('%F %T(%Z)')}. #{string}" end |
#track_time {|block| ... } ⇒ Object
returns spent time in milliseconds
19 20 21 22 23 |
# File 'lib/ext/kernel.rb', line 19 def track_time(&block) start = Time.now yield block (Time.now - start).round(3) * 1000 end |
#try_to(attempt = 1, &block) ⇒ Object
retrying code ‘attempt’ times with delay ‘attempt’ ** 2. If last attempt failed - returns nil.
4 5 6 7 8 9 10 11 12 13 14 15 16 |
# File 'lib/ext/kernel.rb', line 4 def try_to(attempt = 1, &block) begin yield rescue => exception if attempt < 5 sleep(attempt ** 2) try_to(attempt + 1, &block) else Airbrake.notify(exception, error_message: "Exception from try_to block: #{exception.}") return nil end end end |