Last active
October 28, 2024 14:04
-
-
Save jvon1904/985092af898767c9db8e29a2fabda731 to your computer and use it in GitHub Desktop.
Ruby - pretty format and copy valid JSON or Ruby Hash to clipboard or pasteboard.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# NB: This method utilizes 'pbcopy' which is only available on MacOS. | |
# | |
# I often find myself in the IRB or Pry console needing to both format a Ruby Hash and copy it to the clipboard. | |
# Here is a covenient method that can accomplish both of those tasks | |
# | |
# Consider this example: | |
# | |
# A co-worker asks you to text them the data from the most recent Post in your Rails app. | |
# | |
# You enter the rails console... | |
# | |
# Post.last.attributes | |
# | |
# => {"id"=>93, | |
# "title"=>"Cool Post", | |
# "created_at"=>Wed, 11 Sep 2024 17:42:24.344998000 UTC +00:00, | |
# "updated_at"=>Wed, 11 Sep 2024 17:42:24.344998000 UTC +00:00} | |
# | |
# cj _ | |
# Copied to clipboard! ๐ | |
# => {"id"=>93, | |
# "title"=>"Cool Post", | |
# "created_at"=>Wed, 11 Sep 2024 17:42:24.344998000 UTC +00:00, | |
# "updated_at"=>Wed, 11 Sep 2024 17:42:24.344998000 UTC +00:00} | |
# | |
# Now you switch over to your messaging service to share it with a co-worker. You copy it into to the message using cmd + v: | |
# | |
# { | |
# "id": 93, | |
# "title": "Cool Post", | |
# "created_at": "2024-09-11T17:42:24.344Z", | |
# "updated_at": "2024-09-11T17:42:24.344Z" | |
# } | |
# | |
# This will work with a valid JSON string or Ruby Hash | |
# | |
# (cj stands for copy JSON) | |
# | |
# | |
require 'json' | |
def cj(obj) | |
unless `uname`.include?('Darwin') | |
$stdout.puts "#cj is only compatible on MacOS" | |
return nil | |
end | |
IO.popen('pbcopy', 'w') do |pipe| | |
content = case obj | |
when String | |
JSON.parse(obj).as_json | |
when Hash | |
obj.as_json | |
end | |
pipe.puts JSON.pretty_generate(content) | |
$stdout.puts "Copied to clipboard! ๐" | |
content | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment