哈囉,大家好!被翻爛的書今天想用插話介紹一個實用的gem——amazing print:
若大家跟我一樣是程式小白,想必會對rails console 資料的解讀有些困擾,如昨天seeding 完假資料後,在console 下Podcast.all
會得到這樣的資訊:
irb(main):001:0> Podcast.all
Podcast Load (0.6ms) SELECT "podcasts".* FROM "podcasts" LIMIT $1 [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<Podcast id: 281, name: "The Man Within", genres: nil, host: "水婉婷", introduction: "Reiciendis et totam. Ad pariatur doloribus. Quibus...", created_at: "2022-09-18 13:38:38", updated_at: "2022-09-18 13:38:38">, #<Podcast id: 282, name: "That Hideous Strength", genres: nil, host: "慕淑萍", introduction: "Ex rerum fuga. Qui perferendis voluptatem. Volupta...", created_at: "2022-09-18 13:38:38", updated_at: "2022-09-18 13:38:38">,
# 後略
甚至連IThome markdown 的程式碼編輯區塊都比console 看到的data 容易解讀!
那麼該怎麼印出漂亮或易讀的data 呢?當然就是用上面提到的amazing print 啦!
Amazing-print 是Awesome-print fork 出來的gem,目前仍有在更新:
效果如下:
看起來應該比上方的資訊好讀吧!?
那我們就來一起安裝囉!
# 直接安裝
gem install amazing_print
# 放入Gemfile + bundle install
# Use to print colorful and readable data in console
gem 'amazing_print', '~> 1.4'
好了之後先別急,還有一步!
若你的console 也是用irb,請在專案下建立.irbrc
:
# 在專案目錄下建立
touch .irbrc
# 編輯.irbrc
require "amazing_print"
AmazingPrint.irb!
若是用pry,則用.pryrc
管理:
require "amazing_print"
AmazingPrint.pry!
此外,該檔案也可以放在home 目錄下的.irbrc
或.pryrc
當global 設定;好了之後就可以進console 試試囉!
注意,如果在query 後顯示跟原本一樣,請先輸入require "amazing_print"
試試,如果有出現下列錯誤:
irb(main):003:0> require "amazing_print"
Traceback (most recent call last):
1: from (irb):3
LoadError (cannot load such file -- amazing_print)
那麼,請先確認自己的amazing_print lib 的目錄,或以下列指令查詢lib 位置:
❯ gem which amazing_print
/Users/xxx/.asdf/installs/ruby/2.5.9/lib/ruby/gems/2.5.0/gems/amazing_print-1.4.0/lib/amazing_print.rb
接著再次編輯.irbrc
:
# 加入第一行
$LOAD_PATH << '/Users/xxx/.asdf/installs/ruby/2.5.9/lib/ruby/gems/2.5.0/gems/amazing_print-1.4.0/lib/'
require 'amazing_print'
AmazingPrint.irb!
接著就能進console 確認是否變漂亮啦!
irb(main):001:0> Podcast.all
Podcast Load (0.5ms) SELECT "podcasts".* FROM "podcasts"
[
[0] #<Podcast:0x00007f8246955450> {
:id => 281,
:name => "The Man Within",
:genres => nil,
:host => "水婉婷",
:introduction => "Reiciendis et totam. Ad pariatur doloribus. Quibusdam ex illum. Eaque eligendi quas. Ipsum labore molestias. Dolorem et labore. Nam non et. Odit asperiores molestias. Debitis qui ratione. Provident quasi dolorem. Aliquid commodi quo. Eligendi aliquid dele.",
:created_at => Sun, 18 Sep 2022 13:38:38 UTC +00:00,
:updated_at => Sun, 18 Sep 2022 13:38:38 UTC +00:00
},
# 略
最後,如果還有其他global 的設定要處理,可在home 目錄下.config
新增一名為aprc
的檔案,並輸入以下指令測試是否都有被縮排、hash data 是否有被改變顏色等:
# ~/.config/aprc file.
AmazingPrint.defaults = {
:indent => -2,
:color => {
:hash => :whiteish,
:class => :white
}
}
以上,歡迎大家一同讓console 的query 一起變得美美的~~ 也能讓我們之後query 出來的資料更好解讀啦!