Writing Ruby Scripts That Respect Pipelines
Guide to writing CLI scripts in Ruby that play nice with pipe chains.
Related cards:
A Ruby script that installs all gems it is missing
So you want your Ruby script to install missing gems instead of dying? Take this method:
def installing_missing_gems(&block)
yield
rescue LoadError => e
gem_name = e.message.split('--').last.strip
install_command = 'gem install ' + gem_...
Ruby GetText will eval scripts containing ActiveRecord classes
When the Ruby parser module of Ruby-GetText comes across a file in one of its search directories (e.g. lib/scripts/
) and finds out that you are defining ActiveRecord classes inside it, **it eva...
List of handy Ruby scripts to transcode different file types (often by using GPT)
It's 2024 and we have tools like ffmpeg, imagemagick and GPT readily available. With them, it's easy to convert texts, images, audio and video clips into each other.
For the everyday use without any parameter tweaking I'm using a collection of ti...
Best practices: Writing a Rails script (and how to test it)
A Rails script lives in lib/scripts and is run with bin/rails runner lib/scripts/...
. They are a simple tool to perform some one-time actions on your Rails application. A Rails script has a few advantages over pasting some prepared code into a R...
Ruby: Writing specs for (partially) memoized code
When you're writing specs for ActiveRecord models that use memoization, a simple #reload
will not do:
it 'updates on changes' do
subject.seat_counts = [5]
subject.seat_total.should == 5
# seat_t...
How to get the hostname of the current machine in Rails or a Ruby script
Use Socket.gethostname
. So for a machine whose hostname is "happycat", it will look like this:
>> Socket.gethostname
=> "happycat"
That should work right away for your Rails application. For plain Ruby, you first need to do:
requi...
How to: Benchmark an Active Record query with a Ruby script
Recently I needed to benchmark an Active Record query for performance measurements. I wrote a small script that runs each query to benchmark 100 times and calculates the 95th percentile.
Note: The script requires sudo permissions to drop RAM cach...
Ruby: Reading and writing CSVs
In ruby you can easily read and write CSVs with the standard CSV library class.
On top of this, you can use the gem smarter_csv f...
Ruby Scripts: Select the Ruby version in the shebang
As Bill Dueber has on his blog, you can call rvm
in the shebang to select a Ruby version like this:
#!/usr/bin/env rvm 1.9 do ruby
Standard arguments to do
apply, see $> rvm help do
.