grosser/parallel
Utility methods to distribute each
or map
over multiple threads or processes.
Related cards:
How to iterate over an Enumerable, returning the first truthy result of a block ("map-find")
Ruby has Enumerable.find(&block)
, which returns the first item in the collection for which the block evaluates to true
.
first_post_with_image = posts.find do |post|
post.image
end
However, sometimes it's not the item you're int...
How to get a backtrace if rspec (or any other ruby process) hangs with no output
If rspec hangs with no output and you dont get a backtrace neither with --backtrace
nor by just killing it with crtl-c,
you can put the following in your spec/spec_helper.rb
:
puts "rspec pid: #{Process.pid}"
trap 'USR1' do
thread...
How to see how many inotify instances are used by each process
As a developer you may have many tools watching your project for changes: Your IDE, Webpack, Guard, etc. This is often done with an inotify watcher. If you have too many inotify instances you may run into limits of your operating system.
To fin...
Useful methods to process tables in Cucumber step definitions
When you accept a table in your Cucumber step definition, that table object will have the cryptic type Cucumber::Ast::Table
. Don't immediately call `table...
The "private" modifier does not apply to class methods or define_method
Ruby's private
keyword might do a lot less than you think.
"private" does not apply to class methods defined on self
This does not make anything private:
class Foo
priva...
Threads and processes in a Capybara/Selenium session
TLDR: This card explains which threads and processes interact with each other when you run a Selenium test with Capybara. This will help you understand "impossible" behavior of your tests.
When you run a Rack::Te...
How to tell ActiveRecord how to preload associations (either JOINs or separate queries)
Remember why preloading associations "randomly" uses joined tables or multiple queries?
If you don't like the cleverness of thi...
Use find_in_batches or find_each to deal with many records efficiently
Occasionally you need to do something directly on the server -- like having all records recalculate something that cannot be done in a migration because it takes a long time.
Let's say you do something like this:
Project.all.each(&:recal...
Ruby: How to collect a Hash from an Array
There are many different methods that allow mapping an Array to a Hash in Ruby.
Array#to_h
with a block (Ruby 2.6+)
You can call an array with a block that is called with each element. The block must return a [key, value]
tuple.
This i...
Ruby: How to convert hex color codes to rgb or rgba
When you have a hex color code, you can easily convert it into its RGB values using plain Ruby.
>> "#ff8000".match(/^#(..)(..)(..)$/).captures.map(&:hex)
=> [255, 128, 0]
You can use that to implement a simple "hex to CSS rgba value ...