如何編寫命令列工具以通過郵政編碼獲取天氣

這將是一個相對全面的教程,介紹如何編寫命令列工具以從提供給命令列工具的郵政編碼中列印天氣。第一步是在 ruby 中編寫程式來執行此操作。讓我們從寫一個方法 weather(zip_code) 開始(這個方法需要 yahoo_weatherman gem。如果你沒有這個 gem 你可以通過從命令列輸入 gem install yahoo_weatherman 來安裝它)

require 'yahoo_weatherman'

def weather(zip_code)
  client = Weatherman::Client.new
  client.lookup_by_location(zip_code).condition['temp']
end

我們現在有一個非常基本的方法,可以在提供郵政編碼時提供天氣。現在我們需要將它變成命令列工具。很快我們來看看如何從 shell 和相關變數呼叫命令列工具。當像 tool argument other_argument 這樣的工具被呼叫時,在 ruby 中有一個變數 ARGV,它是一個等於 ['argument', 'other_argument'] 的陣列。現在讓我們在我們的應用程式中實現它

#!/usr/bin/ruby
require 'yahoo_weatherman'

def weather(zip_code)
  client = Weatherman::Client.new
  client.lookup_by_location(zip_code).condition['temp']
end 
 
puts weather(ARGV[0])

好! 現在我們有一個可以執行的命令列應用程式。注意檔案開頭的 she-bang 行(#!/usr/bin/ruby)。這允許檔案成為可執行檔案。我們可以將此檔案儲存為 weather。 ( 注意 :不要將其儲存為 weather.rb,不需要副檔名,並且 she-bang 告訴你需要告訴你這是一個 ruby 檔案)。現在我們可以在 shell 中執行這些命令(不要輸入 $)。

$ chmod a+x weather
$ ./weather [ZIPCODE]

在測試完成後,我們現在可以通過執行此命令將其與/usr/bin/local/進行 sym-link 連線

$ sudo ln -s weather /usr/local/bin/weather

現在可以在命令列上呼叫 weather,無論你在哪個目錄中。