weather_api_client 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f7cf0d2ddaaa35d3eba48c4df62cd56148b933410e49a68904a7184d08eb72e2
4
+ data.tar.gz: 444c83f4ef4f59eb50bd9e17f59d7252f0b77df401d15f2559050534c56b45b9
5
+ SHA512:
6
+ metadata.gz: f78e7784e9a82729ca424252b802be69ca4c1b7448f3ecfff2020bb2f7355106f423a871cd8f71d35061a94c1187d84d1580171e27060f9b5e45a0b3a557ab2e
7
+ data.tar.gz: 13f642c817ab614ca1d5ae4e2231b85f77ff3c90cd1a1a394c382b42f03135cb697812b06ef7102a85b0d9d2abe5170cb4afaf8def7e8acd00606a743ab1ca86
data/.idea/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ # Default ignored files
2
+ /shelf/
3
+ /workspace.xml
4
+ # Ignored default folder with query files
5
+ /queries/
6
+ # Datasource local storage ignored files
7
+ /dataSources/
8
+ /dataSources.local.xml
9
+ # Editor-based HTTP Client requests
10
+ /httpRequests/
data/.idea/.name ADDED
@@ -0,0 +1 @@
1
+ console
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="AmplicodeJpaIdeaProjectConfig">
4
+ <option name="renamerInitialized" value="true" />
5
+ </component>
6
+ </project>
data/.idea/misc.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectType">
4
+ <option name="id" value="jpab" />
5
+ </component>
6
+ </project>
data/.idea/modules.xml ADDED
@@ -0,0 +1,8 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="ProjectModuleManager">
4
+ <modules>
5
+ <module fileurl="file://$PROJECT_DIR$/.idea/weather_api_client.iml" filepath="$PROJECT_DIR$/.idea/weather_api_client.iml" />
6
+ </modules>
7
+ </component>
8
+ </project>
data/.idea/vcs.xml ADDED
@@ -0,0 +1,6 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <project version="4">
3
+ <component name="VcsDirectoryMappings">
4
+ <mapping directory="" vcs="Git" />
5
+ </component>
6
+ </project>
@@ -0,0 +1,34 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <module type="RUBY_MODULE" version="4">
3
+ <component name="ModuleRunConfigurationManager">
4
+ <shared />
5
+ </component>
6
+ <component name="NewModuleRootManager">
7
+ <content url="file://$MODULE_DIR$">
8
+ <sourceFolder url="file://$MODULE_DIR$/features" isTestSource="true" />
9
+ <sourceFolder url="file://$MODULE_DIR$/spec" isTestSource="true" />
10
+ <sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
11
+ </content>
12
+ <orderEntry type="jdk" jdkName="ruby-3.4.8-p72" jdkType="RUBY_SDK" />
13
+ <orderEntry type="sourceFolder" forTests="false" />
14
+ <orderEntry type="library" scope="PROVIDED" name="ansi (v1.5.0, ruby-3.4.8-p72) [gem]" level="application" />
15
+ <orderEntry type="library" scope="PROVIDED" name="bigdecimal (v4.0.1, ruby-3.4.8-p72) [gem]" level="application" />
16
+ <orderEntry type="library" scope="PROVIDED" name="builder (v3.3.0, ruby-3.4.8-p72) [gem]" level="application" />
17
+ <orderEntry type="library" scope="PROVIDED" name="bundler (v2.6.9, ruby-3.4.8-p72) [gem]" level="application" />
18
+ <orderEntry type="library" scope="PROVIDED" name="csv (v3.3.5, ruby-3.4.8-p72) [gem]" level="application" />
19
+ <orderEntry type="library" scope="PROVIDED" name="diff-lcs (v1.6.2, ruby-3.4.8-p72) [gem]" level="application" />
20
+ <orderEntry type="library" scope="PROVIDED" name="httparty (v0.24.2, ruby-3.4.8-p72) [gem]" level="application" />
21
+ <orderEntry type="library" scope="PROVIDED" name="mini_mime (v1.1.5, ruby-3.4.8-p72) [gem]" level="application" />
22
+ <orderEntry type="library" scope="PROVIDED" name="minitest (v5.27.0, ruby-3.4.8-p72) [gem]" level="application" />
23
+ <orderEntry type="library" scope="PROVIDED" name="minitest-reporters (v1.7.1, ruby-3.4.8-p72) [gem]" level="application" />
24
+ <orderEntry type="library" scope="PROVIDED" name="multi_xml (v0.8.1, ruby-3.4.8-p72) [gem]" level="application" />
25
+ <orderEntry type="library" scope="PROVIDED" name="rake (v13.3.1, ruby-3.4.8-p72) [gem]" level="application" />
26
+ <orderEntry type="library" scope="PROVIDED" name="rspec (v3.13.2, ruby-3.4.8-p72) [gem]" level="application" />
27
+ <orderEntry type="library" scope="PROVIDED" name="rspec-core (v3.13.6, ruby-3.4.8-p72) [gem]" level="application" />
28
+ <orderEntry type="library" scope="PROVIDED" name="rspec-expectations (v3.13.5, ruby-3.4.8-p72) [gem]" level="application" />
29
+ <orderEntry type="library" scope="PROVIDED" name="rspec-mocks (v3.13.8, ruby-3.4.8-p72) [gem]" level="application" />
30
+ <orderEntry type="library" scope="PROVIDED" name="rspec-support (v3.13.7, ruby-3.4.8-p72) [gem]" level="application" />
31
+ <orderEntry type="library" scope="PROVIDED" name="ruby-progressbar (v1.13.0, ruby-3.4.8-p72) [gem]" level="application" />
32
+ <orderEntry type="library" scope="PROVIDED" name="test_helper (v0.0.1, ruby-3.4.8-p72) [gem]" level="application" />
33
+ </component>
34
+ </module>
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2026-03-22
4
+
5
+ - Initial release
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2026 TODO: Write your name
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,50 @@
1
+ # Weather API Client
2
+
3
+ Учебный проект на языке **Ruby**, разработанный в рамках курса «Прикладная математика и информатика» (ПМИ-3).
4
+ Приложение представляет собой консольный клиент для работы с API **OpenWeatherMap**, поддерживающий получение текущей погоды и прогноза на 5 дней.
5
+
6
+ ---
7
+
8
+ ## Наша команда (ПМИ-3)
9
+ * **Сергей Донец** — Lead Engineer: Архитектура проекта, интеграция модулей, настройка сборки и RSpec тестирование.
10
+ * **Егор Сурнев** — Backend Developer: Разработка сетевого клиента (`Client`) и взаимодействие с API.
11
+ * **Эдуард Лущевич** — Data Engineer: Разработка парсера данных (`Parser`) и обработка JSON структур.
12
+ * **Арсений Ковалев** — UI/UX Developer: Проектирование консольного интерфейса (`CLI`) и цветовая визуализация.
13
+
14
+ ---
15
+
16
+ ## Технологический стек
17
+ * **Ruby 3.1+**
18
+ * **HTTParty** — выполнение сетевых запросов.
19
+ * **Colorize** — цветовое оформление консольного вывода.
20
+ * **RSpec** — модульное тестирование.
21
+ * **JSON** — обработка ответов от API.
22
+
23
+ ---
24
+
25
+ ## Установка
26
+
27
+ 1. **Клонируйте репозиторий:**
28
+ git clone [https://github.com/Chacha-Muchacha/weather_api_client.git](https://github.com/Chacha-Muchacha/weather_api_client.git)
29
+ cd weather_api_client
30
+
31
+ 2. **Установите зависимости (библиотеки):**
32
+ bundle install
33
+
34
+ 3. **Как пользоваться:**
35
+ Для запуска приложения выполните команду из корневой папки проекта:
36
+ ruby -Ilib -e "require 'weather_api_client'; WeatherApiClient.run"
37
+
38
+ После запуска введите название города на английском. Например Moscow или London.
39
+
40
+ Выберите режим:
41
+
42
+ 1 — Текущая погода (температура, влажность, описание).
43
+
44
+ 2 — Прогноз на 5 дней (с шагом в 6 часов).
45
+
46
+ Для выхода из программы введите exit.
47
+
48
+ 4. **Тестирование:**
49
+ Мы используем RSpec для проверки корректности парсинга данных. Чтобы убедиться, что всё работает правильно, запустите:
50
+ bundle exec rspec
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,129 @@
1
+ require_relative 'client'
2
+ require_relative 'parser'
3
+ require 'colorize'
4
+
5
+ module WeatherApiClient
6
+ # Класс для управления консольным интерфейсом приложения.
7
+ class CLI
8
+ # Запускает основной цикл программы.
9
+ # @return [void]
10
+ def self.start
11
+ puts "🌦️ Welcome to Weather API Client! 🌍".light_blue
12
+ puts "Type 'exit' to quit.\n\n"
13
+
14
+ loop do
15
+ print "Enter city name (or 'exit' to quit): "
16
+ input = gets.chomp.strip
17
+ break if input.downcase == 'exit'
18
+
19
+ if input.empty?
20
+ puts "⚠️ Please enter a city name.\n\n".yellow
21
+ next
22
+ end
23
+
24
+ puts "\nWhat do you want to see?"
25
+ puts " 1. Current weather"
26
+ puts " 2. 5-day forecast"
27
+ print "Your choice (1 or 2): "
28
+ choice = gets.chomp.strip
29
+
30
+ case choice
31
+ when "1"
32
+ show_current_weather(input)
33
+ when "2"
34
+ show_forecast(input)
35
+ else
36
+ puts "❌ Invalid choice, please enter 1 or 2.\n\n".red
37
+ end
38
+ end
39
+
40
+ puts "👋 Goodbye!"
41
+ end
42
+
43
+ private
44
+
45
+ # Получает и выводит текущую погоду для города.
46
+ # @param city [String] название города.
47
+ def self.show_current_weather(city)
48
+ begin
49
+ raw_json = WeatherApiClient::Client.fetch_weather(city)
50
+ data = WeatherApiClient::Parser.new.parse_all_coord_city(raw_json)
51
+
52
+ temp = data[:temperature]
53
+ condition = data[:condition]
54
+ humidity = data[:humidity]
55
+
56
+ colored_temp = colorize_temp(temp)
57
+
58
+ puts "\n📍 Weather in #{city.capitalize}:"
59
+ puts " 🌡️ Temperature: #{colored_temp}"
60
+ puts " ☁️ Condition: #{condition.capitalize}"
61
+ puts " 💧 Humidity: #{humidity}%"
62
+ puts ""
63
+ rescue StandardError => e
64
+ puts "❌ Error: #{e.message}\n\n".red
65
+ end
66
+ end
67
+
68
+ # Получает и выводит прогноз погоды на 5 дней.
69
+ # @param city [String] название города.
70
+ def self.show_forecast(city)
71
+ begin
72
+ forecast_raw = WeatherApiClient::Client.fetch_forecast(city)
73
+ parser = WeatherApiClient::Parser.new
74
+ forecast_data = parser.parse_all_forecast(forecast_raw)
75
+
76
+ temps = forecast_data[:temperature]
77
+ conditions = forecast_data[:condition]
78
+ humidities = forecast_data[:humidity]
79
+
80
+ target_hours = [0, 6, 12, 18]
81
+ forecast_by_day = {}
82
+
83
+ temps.each do |datetime_str, temp|
84
+ date_part, time_part = datetime_str.split(' ')
85
+ hour = time_part.split(':')[0].to_i
86
+ next unless target_hours.include?(hour)
87
+
88
+ forecast_by_day[date_part] ||= {}
89
+ forecast_by_day[date_part][hour] = {
90
+ temp: temp,
91
+ condition: conditions[datetime_str],
92
+ humidity: humidities[datetime_str],
93
+ time: time_part
94
+ }
95
+ end
96
+
97
+ puts "\n📅 5-day forecast (every 6 hours):\n\n"
98
+ forecast_by_day.sort.first(5).each do |date, hours_data|
99
+ puts "📆 #{date}:"
100
+ [0, 6, 12, 18].each do |hour|
101
+ data = hours_data[hour]
102
+ if data
103
+ colored_temp = colorize_temp(data[:temp])
104
+ puts " #{data[:time]} 🌡️ #{colored_temp} ☁️ #{data[:condition].capitalize} 💧 #{data[:humidity]}%"
105
+ else
106
+ puts " #{hour}:00 ⚠️ Data not available"
107
+ end
108
+ end
109
+ puts ""
110
+ end
111
+ rescue StandardError => e
112
+ puts "❌ Error fetching forecast: #{e.message}\n\n".red
113
+ end
114
+ end
115
+
116
+ # Раскрашивает значение температуры в зависимости от её величины.
117
+ # @param temp [Float, Integer] значение температуры.
118
+ # @return [String] раскрашенная строка для вывода.
119
+ def self.colorize_temp(temp)
120
+ if temp > 20
121
+ "#{temp}°C".red
122
+ elsif temp < 0
123
+ "#{temp}°C".blue
124
+ else
125
+ "#{temp}°C".green
126
+ end
127
+ end
128
+ end
129
+ end
@@ -0,0 +1,3 @@
1
+ module WeatherApiClient
2
+ class Error < StandardError; end
3
+ end
@@ -0,0 +1,22 @@
1
+ require 'httparty'
2
+
3
+ module WeatherApiClient
4
+ class Client
5
+ module Geo
6
+ URL = "http://api.openweathermap.org/geo/1.0/direct"
7
+
8
+ def self.fetch_coords(city, api_key)
9
+ options = { query: { q: city, limit: 1, appid: api_key } }
10
+ response = HTTParty.get(URL, options)
11
+
12
+ if response.success? && !response.parsed_response.empty?
13
+ # Берем первый город из списка результатов
14
+ data = response.parsed_response.first
15
+ { lat: data["lat"], lon: data["lon"], name: data["name"] }
16
+ else
17
+ raise WeatherApiClient::Error, "Город '#{city}' не найден через Geo API"
18
+ end
19
+ end
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,44 @@
1
+ require 'httparty'
2
+
3
+ module WeatherApiClient
4
+ class Client
5
+ module WeatherData
6
+ CURRENT_URL = "https://api.openweathermap.org/data/2.5/weather"
7
+ FORECAST_URL = "https://api.openweathermap.org/data/2.5/forecast"
8
+
9
+ # 1. Погода по названию города (то, что было)
10
+ def self.fetch_by_city(city, api_key)
11
+ params = { q: city, units: 'metric', lang: 'ru' }
12
+ make_request(CURRENT_URL, params, api_key)
13
+ end
14
+
15
+ # 2. Погода по точным координатам (широта и долгота)
16
+ def self.fetch_by_coords(lat, lon, api_key)
17
+ params = { lat: lat, lon: lon, units: 'metric', lang: 'ru' }
18
+ make_request(CURRENT_URL, params, api_key)
19
+ end
20
+
21
+ # 3. Прогноз погоды на 5 дней (шаг 3 часа)
22
+ def self.fetch_forecast(city, api_key)
23
+ params = { q: city, units: 'metric', lang: 'ru' }
24
+ make_request(FORECAST_URL, params, api_key)
25
+ end
26
+
27
+ private
28
+
29
+ # Вспомогательный метод, чтобы не писать HTTParty.get и проверки каждый раз
30
+ def self.make_request(url, params, api_key)
31
+ options = { query: params.merge(appid: api_key) }
32
+
33
+ response = HTTParty.get(url, options)
34
+
35
+ if response.success?
36
+ response.body
37
+ else
38
+ error_detail = response.parsed_response['message'] rescue "Ошибка сервера"
39
+ raise WeatherApiClient::Error, "Ошибка API (#{response.code}): #{error_detail}"
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,48 @@
1
+ require_relative 'client/errors'
2
+ require_relative 'client/geo'
3
+ require_relative 'client/weather_data'
4
+
5
+ module WeatherApiClient
6
+ # Основной класс для взаимодействия с Weather API.
7
+ # Предоставляет методы для получения текущей погоды и прогнозов.
8
+ class Client
9
+ API_KEY = "d83dc87e13390e61b47db6189845d913"
10
+
11
+ # Получает текущую погоду для указанного города.
12
+ #
13
+ # @param city [String] Название города (например, "Moscow" или "London,uk").
14
+ # @return [String] JSON-ответ от API с данными о текущей погоде.
15
+ # @raise [WeatherApiClient::Error] Если город не найден или произошла ошибка API.
16
+ #
17
+ # @example Получение погоды для Москвы
18
+ # WeatherApiClient::Client.fetch_weather("Moscow")
19
+ def self.fetch_weather(city)
20
+ WeatherData.fetch_by_city(city, API_KEY)
21
+ end
22
+
23
+ # Получает прогноз погоды на 5 дней с шагом в 3 часа.
24
+ #
25
+ # @param city [String] Название города.
26
+ # @return [String] JSON-ответ от API с данными прогноза.
27
+ # @raise [WeatherApiClient::Error] Если API вернуло ошибку.
28
+ #
29
+ # @example Получение прогноза
30
+ # WeatherApiClient::Client.fetch_forecast("London")
31
+ def self.fetch_forecast(city)
32
+ WeatherData.fetch_forecast(city, API_KEY)
33
+ end
34
+
35
+ # Получает текущую погоду по географическим координатам.
36
+ #
37
+ # @param lat [Float, String] Широта.
38
+ # @param lon [Float, String] Долгота.
39
+ # @return [String] JSON-ответ от API.
40
+ # @raise [WeatherApiClient::Error] Если координаты неверны или API недоступно.
41
+ #
42
+ # @example Поиск по координатам
43
+ # WeatherApiClient::Client.fetch_by_coords(55.75, 37.61)
44
+ def self.fetch_by_coords(lat, lon)
45
+ WeatherData.fetch_by_coords(lat, lon, API_KEY)
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,61 @@
1
+ require 'json'
2
+
3
+ module WeatherApiClient
4
+ # Класс для парсинга и извлечения данных из ответов OpenWeather API.
5
+ class Parser
6
+ # Преобразует строку JSON в хэш с символьными ключами.
7
+ # @param json_string [String] JSON-ответ.
8
+ # @return [Hash] десериализованные данные.
9
+ # @raise [RuntimeError] если формат JSON невалиден.
10
+ def parse(json_string)
11
+ JSON.parse(json_string, symbolize_names: true)
12
+ rescue JSON::ParserError => e
13
+ raise "Failed to parse JSON response: #{e.message}"
14
+ end
15
+
16
+ # Извлекает данные о текущей погоде.
17
+ # @param json_string [String] JSON-ответ.
18
+ # @return [Hash] хэш с температурой, влажностью и описанием.
19
+ def parse_all_coord_city(json_string)
20
+ ddata = parse(json_string)
21
+ {
22
+ temperature: ddata.dig(:main, :temp),
23
+ humidity: ddata.dig(:main, :humidity),
24
+ condition: ddata.dig(:weather, 0, :description)
25
+ }
26
+ end
27
+
28
+ # Извлекает данные прогноза на 5 дней.
29
+ # @param json_string [String] JSON-ответ.
30
+ # @return [Hash] хэш со списками температур, влажности и состояний по времени.
31
+ def parse_all_forecast(json_string)
32
+ ddata = parse(json_string)
33
+ {
34
+ temperature: extract_forecast_field(ddata, [:main, :temp]),
35
+ humidity: extract_forecast_field(ddata, [:main, :humidity]),
36
+ condition: extract_forecast_field(ddata, [:weather, 0, :description])
37
+ }
38
+ end
39
+
40
+ private
41
+
42
+ # Универсальный метод для извлечения полей из списка прогнозов.
43
+ # @param data [Hash] спарсенный JSON.
44
+ # @param keys [Array] путь к полю в структуре данных.
45
+ # @return [Hash] словарь { время => значение }.
46
+ def extract_forecast_field(data, keys)
47
+ list = data.dig(:list)
48
+ return {} unless list
49
+
50
+ result = {}
51
+ list.each do |entry|
52
+ time = entry.dig(:dt_txt)
53
+ value = entry.dig(keys[0], keys[1]) if keys.size == 2
54
+ value = entry.dig(keys[0], 0, keys[2]) if keys.size == 3 # для weather[0].description
55
+
56
+ result[time] = value if time && value
57
+ end
58
+ result
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WeatherApiClient
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "weather_api_client/version"
4
+ require_relative "weather_api_client/client"
5
+ require_relative "weather_api_client/parser"
6
+ require_relative "weather_api_client/cli"
7
+
8
+ module WeatherApiClient
9
+ class Error < StandardError; end
10
+
11
+ # Это метод, который можно будет вызвать из консоли
12
+ def self.run
13
+ CLI.start
14
+ end
15
+ end
@@ -0,0 +1,4 @@
1
+ module WeatherApiClient
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,123 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: weather_api_client
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Sergey Donets
8
+ - Egor Surnev
9
+ - Eduard Lushchevich
10
+ - Arseniy Kovalev
11
+ bindir: exe
12
+ cert_chain: []
13
+ date: 2026-04-09 00:00:00.000000000 Z
14
+ dependencies:
15
+ - !ruby/object:Gem::Dependency
16
+ name: httparty
17
+ requirement: !ruby/object:Gem::Requirement
18
+ requirements:
19
+ - - "~>"
20
+ - !ruby/object:Gem::Version
21
+ version: 0.21.0
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - "~>"
27
+ - !ruby/object:Gem::Version
28
+ version: 0.21.0
29
+ - !ruby/object:Gem::Dependency
30
+ name: colorize
31
+ requirement: !ruby/object:Gem::Requirement
32
+ requirements:
33
+ - - "~>"
34
+ - !ruby/object:Gem::Version
35
+ version: '1.1'
36
+ type: :runtime
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - "~>"
41
+ - !ruby/object:Gem::Version
42
+ version: '1.1'
43
+ - !ruby/object:Gem::Dependency
44
+ name: rspec
45
+ requirement: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - "~>"
48
+ - !ruby/object:Gem::Version
49
+ version: '3.0'
50
+ type: :development
51
+ prerelease: false
52
+ version_requirements: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - "~>"
55
+ - !ruby/object:Gem::Version
56
+ version: '3.0'
57
+ - !ruby/object:Gem::Dependency
58
+ name: rake
59
+ requirement: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - "~>"
62
+ - !ruby/object:Gem::Version
63
+ version: '13.0'
64
+ type: :development
65
+ prerelease: false
66
+ version_requirements: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - "~>"
69
+ - !ruby/object:Gem::Version
70
+ version: '13.0'
71
+ description: A Ruby gem that provides current weather and 5-day forecast using OpenWeatherMap
72
+ API with a colorized CLI.
73
+ email:
74
+ - sdonec3@gmail.com
75
+ executables: []
76
+ extensions: []
77
+ extra_rdoc_files: []
78
+ files:
79
+ - ".idea/.gitignore"
80
+ - ".idea/.name"
81
+ - ".idea/amplicode-jpa.xml"
82
+ - ".idea/misc.xml"
83
+ - ".idea/modules.xml"
84
+ - ".idea/vcs.xml"
85
+ - ".idea/weather_api_client.iml"
86
+ - ".rspec"
87
+ - CHANGELOG.md
88
+ - CODE_OF_CONDUCT.md
89
+ - LICENSE.txt
90
+ - README.md
91
+ - Rakefile
92
+ - lib/weather_api_client.rb
93
+ - lib/weather_api_client/cli.rb
94
+ - lib/weather_api_client/client.rb
95
+ - lib/weather_api_client/client/errors.rb
96
+ - lib/weather_api_client/client/geo.rb
97
+ - lib/weather_api_client/client/weather_data.rb
98
+ - lib/weather_api_client/parser.rb
99
+ - lib/weather_api_client/version.rb
100
+ - sig/weather_api_client.rbs
101
+ homepage: https://github.com/Chacha-Muchacha/weather_api_client
102
+ licenses:
103
+ - MIT
104
+ metadata:
105
+ source_code_uri: https://github.com/Chacha-Muchacha/weather_api_client
106
+ rdoc_options: []
107
+ require_paths:
108
+ - lib
109
+ required_ruby_version: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - ">="
112
+ - !ruby/object:Gem::Version
113
+ version: 3.1.0
114
+ required_rubygems_version: !ruby/object:Gem::Requirement
115
+ requirements:
116
+ - - ">="
117
+ - !ruby/object:Gem::Version
118
+ version: '0'
119
+ requirements: []
120
+ rubygems_version: 3.6.2
121
+ specification_version: 4
122
+ summary: Console weather client for PMI-3 university project
123
+ test_files: []