Ruby Snippets for Alfred and PopClip

hese are all Ruby snippets intended as templates for using Ruby with the Mac apps Alfred or PopClip. Unfortunately, PopClip no longer accepts user-submitted Ruby code through its website, but you can still use these snippets on your own.

Reformatting dates

Alfred

The script below reformats a date formatted as mm/dd/yyyy into yyyy-mm-dd format. I use this in an Alfred workflow with a Universal Action, so I can select the date, press the Universal Action shortcut, select the workflow, and it will paste the updated text, replacing the selection. Neat and quick! CMD-Z backs out the change if the code borks your text.


#!/usr/bin/env /Users/xxxx/.rbenv/versions/4.0.2/bin/ruby
# frozen_string_literal: true

# print RUBY_VERSION
data = ARGV[0]

if data.size == 8 && Float(data, exception: false)
  date_hash = { month: data[0, 2], day: data[2, 2], year: data[-4, 4] }
  print "#{date_hash[:year]}-#{date_hash[:month]}-#{date_hash[:day]}"
else
  print "#{data}...bad data..."
end
                

PopClip

PopClip needs the 3rd and 4th commented lines below to be present in code. You will have to select the entire text of the file, right click (I think) and choose the import to PopClip option. Once you do that when you select text you should see the name element of the object on line 4 in the pop-up that pop clip presents. Select it to run the code. The code gets the selected text from the ENV['POPCLIP_TEXT'].chomp. I believe that this should work in other languages but change chomp to whatever works in that language.

Alfred passes your selection to the code in ARGV[0]. The workflow itself uses the Universal Action trigger, a shell script component, and then a paste component. I’ll attach the workflow for download below.

The Alfred code should also run from the command line if you pass the input as the first argument. PopClip works a little differently...


#!/usr/bin/env /Users/xxxx/.rbenv/versions/4.0.2/bin/ruby
# frozen_string_literal: true
# #popclip
# { name: ISO 8601, icon: 🗓, after: paste-result }

data = ENV['POPCLIP_TEXT'].chomp

if data.size == 8 && Float(data, exception: false)
  date_hash = { month: data[0, 2], day: data[2, 2], year: data[-4, 4] }
  print "#{date_hash[:year]}-#{date_hash[:month]}-#{date_hash[:day]}"
else
  print "#{data}...bad data..."
end