Module: Kernel
- Defined in:
- lib/ext/kernel.rb
Instance Method Summary collapse
-
#each_with_progress(collection, sql_logging: false, batch: true) ⇒ 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, sql_logging: false, batch: true) ⇒ 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 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 |
# File 'lib/ext/kernel.rb', line 26 def each_with_progress(collection, sql_logging: false, batch: true) progress = 0 all_count = collection.count puts_with_time "Found before: #{all_count} items." i = 0 unless sql_logging old_logger = ActiveRecord::Base.logger ActiveRecord::Base.logger = nil end iterator_proc = Proc.new do |item| yield item, i 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 i = i + 1 end batch && collection.class.superclass.to_s == 'ActiveRecord::Relation' ? collection.find_each(batch_size: 1000) { |item| iterator_proc.call(item) } : collection.each { |item| iterator_proc.call(item) } unless sql_logging ActiveRecord::Base.logger = old_logger end puts_with_time "Left after: #{collection.count} items." rescue => e ActiveRecord::Base.logger = old_logger if old_logger raise e end |
#puts_with_time(string) ⇒ Object
65 66 67 |
# File 'lib/ext/kernel.rb', line 65 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 |