generalistからspecialistへ

一点集中化計画

apiでお天気を引いて来る練習

3日先までの気温、天気を取得して保存する練習をしました

Makefile

weather:
    ruby ./ruby/weather.rb

weather.rb

require "net/http"
require "uri"
require "json"

# 参考 https://auto-worker.com/blog/?p=7739
# https://www.weatherapi.com/my/ で取得
API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXX"
CITY = "Obihiro"
# 無料プランは3日先までforecastできる
DAYS = 3
# 履歴保存場所
HISTORY_PATH = "./ruby/history/weather.txt"

def main
    url = URI.parse("https://api.weatherapi.com/v1/forecast.json?key=#{API_KEY}&q=#{CITY}&days=#{DAYS}&aqi=no&alerts=no")

    response = Net::HTTP.get_response(url)
    forecastdays = JSON.parse(response.body)["forecast"]["forecastday"]

    filtered_data = filtered(forecastdays)

    insert_dates(filtered_data)
end

def filtered(forecastdays)
    forecastdays.map do |f|
        {
            "date": f["date"],
            "mintemp_c": f["day"]["mintemp_c"],
            "maxtemp_c": f["day"]["maxtemp_c"],
            "condition": f["day"]["condition"]["text"]
        }
    end
end

def insert_dates(filtered_data)
    # dateがすでに存在していたらその日付のデータは書き込まない
    filtered_data.each do |f|
        File.open(HISTORY_PATH, "a") do |file|
            file.puts "#{f[:date]}, #{f[:mintemp_c]}, #{f[:maxtemp_c]}, #{f[:condition]}" \
            unless existed_dates().include?(f[:date])
        end
    end
end

def existed_dates
    existed_dates = []
    File.open(HISTORY_PATH, "r") do |file|
        file.each_line do |line|
            existed_dates << line.split(",")[0]  # 既存のdateを代入
        end
    end
    existed_dates
end

main

実行

$ make weather

こんな感じでtextファイルに保存 履歴はずっと残っていく

date, min_temperature, max_temperature, condition
2023-10-08, 6.3, 15.6, Partly cloudy
2023-10-09, 4.7, 16.3, Sunny
2023-10-10, 8.3, 17.3, Moderate rain