Skip to content

Instantly share code, notes, and snippets.

@anchietajunior
Created August 17, 2025 00:06
Show Gist options
  • Select an option

  • Save anchietajunior/86a45b76dd1f0fbc575fa2f179941751 to your computer and use it in GitHub Desktop.

Select an option

Save anchietajunior/86a45b76dd1f0fbc575fa2f179941751 to your computer and use it in GitHub Desktop.
API Climates
require 'httparty'
class WeatherstackClient
API_BASE = "http://api.weatherstack.com"
API_KEY = ""
def current_weather(city)
url = "#{API_BASE}/current"
response = HTTParty.get(url, query: {
access_key: API_KEY,
query: city,
units: "m", # m = Celsius
})
if response.success? && !response["error"]
{
cidade: response["location"]["name"],
pais: response["location"]["country"],
temperatura_c: response["current"]["temperature"],
sensacao_termica_c: response["current"]["feelslike"],
condicao: response["current"]["weather_descriptions"].join(", "),
umidade: response["current"]["humidity"],
vento_kph: response["current"]["wind_speed"]
}
else
{ erro: response["error"] ? response["error"]["info"] : "Não foi possível obter os dados." }
end
rescue SocketError => e
{ erro: "Falha de conexão: #{e.message}" }
rescue => e
{ erro: e.message }
end
end
class OpenMeteoClient
GEO_BASE = "https://geocoding-api.open-meteo.com/v1/search"
METEO_BASE = "https://api.open-meteo.com/v1/forecast"
# Retorna clima atual para uma cidade (ex.: "Paulo Afonso", "São Paulo")
def current_weather(city, country: nil)
place = geocode(city, country: country)
raise "Cidade não encontrada" unless place
params = {
latitude: place[:lat],
longitude: place[:lon],
current_weather: true, # retorna temp, vento, weathercode etc.
temperature_unit: "celsius",
windspeed_unit: "kmh",
timezone: "auto" # usa timezone local do cliente
}
res = HTTParty.get(METEO_BASE, query: params)
raise("HTTP #{res.code}") unless res.success?
cw = res.dig("current_weather") || {}
{
cidade: place[:name],
regiao: [place[:admin1], place[:country]].compact.join(", "),
lat: place[:lat],
lon: place[:lon],
temp_c: cw["temperature"],
vento_kmh: cw["windspeed"],
direcao_vento: cw["winddirection"],
codigo_condicao: cw["weathercode"], # você pode mapear para texto depois
horario: cw["time"]
}
rescue => e
{ erro: e.message }
end
private
# Geocoding pelo Open-Meteo: retorna o 1º resultado
def geocode(city, country: nil)
q = country ? "#{city}, #{country}" : city
res = HTTParty.get(GEO_BASE, query: { name: q, count: 1, language: "pt", format: "json" })
raise("HTTP #{res.code}") unless res.success?
g = Array(res["results"]).first
return nil unless g
{
name: g["name"],
admin1: g["admin1"],
country:g["country"],
lat: g["latitude"],
lon: g["longitude"]
}
end
end
# Exemplo de uso:
# c = WeatherstackClient.new
# puts c.current_weather("São Paulo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment