Четверг, 13 июля 2017 21:48

Sypex Geo на Ruby on Rails

Оцените материал
(0 голосов)

Статья демонстрирует форк описанного в материале OpenWeatherMap API: еще один погодный информер на Ruby on Rails информера, в нынешней своей ипостаси построенного на геме sypex_geo (добавляем в Gemfile: gem 'sypex_geo', также не забудьте gem 'httparty') и выводящего погоду для пула (по умолчанию 10) населенных пунктов, соответствующих ip посетителя сайта.

 

Блог на рельсах. Live Demo.

 

Dev banner 3

 

controller

class WeatherController < ApplicationController
  def one
require 'sypex_geo'
db = SypexGeo::Database.new('./SxGeoCity.dat')
location = db.query(request.remote_ip)

@location = location.city[:lat],location.city[:lon]
@region = location.region[:name_en]
@country = location.country[:name_en]
@country_code = location.country_code
@ip = request.remote_ip

    @cities = "lat=#{location.city[:lat]}&lon=#{location.city[:lon]}"
    @lookup = Weather.call(@cities)
    @temp = Weather.max_value(Weather.make_hash(@lookup, "temp"))
    @pressure = Weather.max_value(Weather.make_hash(@lookup, "pressure"))
    @humidity = Weather.min_value(Weather.make_hash(@lookup, "humidity"))
    @clouds = Weather.min_value(Weather.cloud_hash(@lookup))

  end
end

 

model

class Weather

  include HTTParty
  base_uri "http://api.openweathermap.org/data/2.5/find?&appid=*************************************&units=metric&cnt=10&"
  format :json
  
  def self.call list_ids
    response = HTTParty.get(base_uri + list_ids)
    body = JSON.parse(response.body)
    list = body["list"]
  end

  #create a hash to store city : temp values 
  def self.make_hash list, value
    hash = Hash.new
      list.each do |l|
        temp = l["main"][value]
        city = l["name"]
        hash[city] = temp
      end
    return hash
  end

  #create hash with city: cloud cover
  def self.cloud_hash list
    hash = Hash.new
      list.each do |l|
        cloud = l["clouds"]["all"]
        city = l["name"]
        hash[city] = cloud
      end
    return hash
  end

  #returns the highest value from a hash
  def self.max_value hash
    hash.max_by{|k,v| v}
  end  

  #returns the lowest value from a hash
  def self.min_value hash
    hash.min_by{ |k,v| v}
  end    

end 

 

view

<div><%= @location %></div>
<div><%= @region %></div>
<div><%= @country %></div>
<div><%= @country_code %></div>

<h1>Weather in your area</h1>
<h4>Weather from ip</h4>

<table class="CitiesTable">
<tr>
    <th>City Name</th>
    <th>Pressure,hPa</th>
    <th>Temperature,°C</th>
    <th>Humidity,%</th>
    <th>Percentage Cloud Cover</th>
    <th>Wind,m/s</th>
    <th>Deg</th>
    <th>Weather condition</th>
  </tr>
  
<% @lookup.each do |l| %>
  <tr>
    <td><%= l["name"] %></td>
    <td><%= l["main"]["pressure"] %></td>
    <td><%= l["main"]["temp"] %></td>
    <td><%= l["main"]["humidity"] %></td>
    <td><%= l["clouds"]["all"] %></td>
    <td><%= l["wind"]["speed"] %></td>
    <td><%= l["wind"]["deg"] %></td>
    <td><%= l["weather"][0]["main"] %></td>
  </tr>
<% end %>
</table>

 

Sypex Geo на Ruby on Rails: продолжение на форуме.

 

Здесь всего лишь концепт, не стесняйтесь хакать и форкать. Не забываем про inspect, также Rails.logger.debug response.body в помощь; при тестировании и отладке на локальной машине опционально в контроллере указать любой реальный ip, иначе Rails вернет ошибку:

 

location = db.query('87.250.250.242')

 

Enjoy!

Последнее изменениеПонедельник, 31 июля 2017 17:50

Оставить комментарий

Добавьте ваш комментарий