Skip to content

Commit

Permalink
In extremis
Browse files Browse the repository at this point in the history
  • Loading branch information
demimismo committed Apr 18, 2010
1 parent 64b388a commit 64bc068
Show file tree
Hide file tree
Showing 14 changed files with 196 additions and 16 deletions.
7 changes: 7 additions & 0 deletions app/controllers/application_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details

before_filter :set_globals

# Load frecuently used contents here to improve performance
def set_globals
@page_title = []
@page_title << 'Modal Kombat'
end
# Scrub sensitive parameters from your log
# filter_parameter_logging :password
end
10 changes: 9 additions & 1 deletion app/controllers/cities_controller.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
class CitiesController < ApplicationController

def index
@cities = City.all :select => 'name, id'
respond_to do |format|
format.js { @cities = City.all :select => 'name, id', :order => 'name asc' }
format.html {
@pedestrian_rank = Dataset.find :all, :order => 'pedestrian_share desc', :conditions => 'year = 2006', :limit => 10
@car_rank = Dataset.find :all, :order => 'motorized_share desc', :conditions => 'year = 2006', :limit => 10
@bike_rank = Dataset.find :all, :order => 'bike_share desc', :conditions => 'year = 2006', :limit => 10
@bus_rank = Dataset.find :all, :order => 'public_transport_share desc', :conditions => 'year = 2006', :limit => 10
}
end
end

def show
Expand Down
23 changes: 22 additions & 1 deletion app/controllers/site_controller.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class SiteController < ApplicationController
def index
if !params[:city1].blank? and !params[:city2].blank?
redirect_to "/#{params[:city1].downcase}-versus-#{params[:city2].downcase}"
redirect_to "/#{sluggify(params[:city1])}-versus-#{sluggify(params[:city2])}"
return
end

Expand All @@ -17,4 +17,25 @@ def index
@bus_rank = Dataset.find :all, :order => 'public_transport_share desc', :conditions => 'year = 2006'
@bus_rank = @bus_rank.select { |v| v.city.country == 'España' }[0..2]
end

def about

end


def sluggify(text)
return nil if text.blank?
if defined?(Unicode)
str = Unicode.normalize_KD(text).gsub(/[^\x00-\x7F]/n,'')
str = str.gsub(/\W+/, '-').gsub(/^-+/,'').gsub(/-+$/,'').downcase
return str
else
str = Iconv.iconv('ascii//translit', 'utf-8', text).to_s
str.gsub!(/\W+/, ' ')
str.strip!
str.downcase!
str.gsub!(/\ +/, '-')
return str
end
end
end
7 changes: 4 additions & 3 deletions app/models/city.rb
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
include Geokit::Geocoders

class City < ActiveRecord::Base
has_slug :source_column => :name, :slug_column => :permalink, :prepend_id => false
has_many :datasets
has_slug :source_column => :name, :slug_column => :permalink, :prepend_id => false, :sync_slug => true
has_many :datasets, :dependent => :destroy
acts_as_mappable


def geocode!
geo = Geokit::Geocoders::MultiGeocoder.geocode(self.name)
if geo.success
self.lat, self.lng = geo.lat, geo.lng
self.name, self.country = geo.city, geo.country
self.country = geo.country
end
self.save
end
Expand Down
28 changes: 28 additions & 0 deletions app/models/dataset.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,31 @@
class Dataset < ActiveRecord::Base
belongs_to :city

# calculo el parámetro que falta en caso de que falte sólo uno, hay varios así
def before_save
modes = ['pedestrian_share', 'motorized_share', 'public_transport_share', 'bike_share']

modes.each do |mode|
modes2 = modes - [mode]
# si el valor actual es nil y el resto de valores no lo son...
if eval("self.#{mode}").nil? and modes2.delete_if { |met| eval("self.#{met}.nil?") }.size == 3
sum = 0
modes2.each { |meth| sum += eval("self.#{meth}") }
eval("self.#{mode} = 100.0 - sum")
end
end
end

def bike_rank
Dataset.count :conditions => ['city_id != ? and bike_share >= ?', self.id, self.bike_share], :order => 'bike_share desc'
end
def pedestrian_rank
Dataset.count :conditions => ['city_id != ? and pedestrian_share >= ? and year = ?', self.id, self.pedestrian_share, self.year], :order => 'pedestrian_share desc'
end
def motorized_rank
Dataset.count :conditions => ['city_id != ? and motorized_share >= ? and year = ?', self.id, self.motorized_share, self.year], :order => 'motorized_share desc'
end
def public_transport_rank
Dataset.count :conditions => ['city_id != ? and public_transport_share >= ? and year = ?', self.id, self.public_transport_share, self.year], :order => 'public_transport_share desc'
end
end
29 changes: 29 additions & 0 deletions app/views/cities/index.html.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<div class="rankings">
<h2>Los que más se mueven a pie</h2>
<ol>
<% @pedestrian_rank.each do |dataset| %>
<li><%= link_to dataset.city.name, city_path(dataset.city) %> <span><%= dataset.pedestrian_share %></span></li>
<% end %>
</ol>

<h2>Los que más se mueven en coche</h2>
<ol>
<% @car_rank.each do |dataset| %>
<li><%= link_to dataset.city.name, city_path(dataset.city) %> <span><%= dataset.motorized_share %></span></li>
<% end %>
</ol>

<h2>Los que más se mueven en bici</h2>
<ol>
<% @bike_rank.each do |dataset| %>
<li><%= link_to dataset.city.name, city_path(dataset.city) %> <span><%= dataset.bike_share %></span></li>
<% end %>
</ol>

<h2>Los que más se mueven en transporte público</h2>
<ol>
<% @bus_rank.each do |dataset| %>
<li><%= link_to dataset.city.name, city_path(dataset.city) %> <span><%= dataset.public_transport_share %></span></li>
<% end %>
</ol>
</div>
22 changes: 17 additions & 5 deletions app/views/cities/show.html.erb
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
<%- @page_title << "Descubre cómo se mueve la gente en #{@city.name}" -%>

<div id="city">

<div class="cab estirar">
<h2><%= @city.name %></h2>
<p><strong>Población: </strong> <%= number_with_delimiter(@city.datasets.last.population, :delimiter => ".") %></p>
<h2><%= @city.name %><%= ", #{@city.country}" unless @city.country.blank? %></h2>
<p><strong>Población: </strong> <%= number_with_delimiter(@city.datasets.last.population, :delimiter => ".") %> habitantes</p>
<% unless @related_cities.blank? %>
<p>Comparar <%= @city.name %> con ciudades de tamaño parecido:
<%- @related_cities.each do |city| -%>
<%= link_to city.city.name, "/#{@city.permalink}-versus-#{city.city.permalink}" %>
<%- end -%>
</p>
<% end %>

<% end %>
</div>


Expand All @@ -19,11 +20,22 @@

<div id="table">
<%= render :partial => 'datatable', :locals => { :table_id => 'datatable', :city => @city } %>

<div id="posiciones">
<h2>De un total de <%= City.count %> ciudades evaluadas...</h2>
<p>A pie es la número <strong><%= @city.datasets.last.pedestrian_rank %></strong></p>
<p>En bici es la número <strong><%= @city.datasets.last.bike_rank %></strong></p>
<p>En transporte público es la número <strong><%= @city.datasets.last.public_transport_rank %></strong></p>
<p>En coche es la número <strong><%= @city.datasets.last.motorized_rank %></strong></p>
</div>

<p>Si quieres puedes ver los <%= link_to "rankings a nivel europeo", cities_path %>.</p>
</div>


<script type="text/javascript">
<%= render :partial => 'pie_chart.js', :locals => { :table_id => 'datatable', :render_to => 'container' } %>
</script>


</div>
</div>
2 changes: 1 addition & 1 deletion app/views/cities/versus.html.erb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<div id="versus" class="estirar">

<h2><%= @city1.name %> vs. <%= @city2.name %></h2>
<h2><%= link_to @city1.name, city_path(@city1) %> vs. <%= link_to @city2.name, city_path(@city2) %></h2>

<div id="c1">
<div id="container"></div>
Expand Down
2 changes: 1 addition & 1 deletion app/views/layouts/application.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="es" lang="es">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Modal Kombat</title>
<title><%= @page_title.reverse.join(' | ') %></title>
<meta name="robots" content="index, follow" />
<script type="text/javascript" src="/javascripts/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="/javascripts/hc/js/highcharts.src.js"></script>
Expand Down
7 changes: 7 additions & 0 deletions app/views/site/about.erb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<p class="claim" style="width: 100%;"">
Modal Kombat es una aplicación construida a partir de datos publicados en el <a href="http://epp.eurostat.ec.europa.eu/">portal Eurostat</a>, concretamente de la sección dedicada al proyecto <a href="http://www.urbanaudit.org">Urban Audit</a>. Los datos están un poco desactualizados, pero sirven para sacar conclusiones sobre la forma que tenemos de desplazarnos en las ciudades europeas.
</p>
<p class="claim" style="width: 100%;"">
Gracias a la gente de <a href="http://www.abredatos.es">Abredatos</a> por darnos una excusa para pasar un fin de semana pensando en <a href="http://en.wikipedia.org/wiki/Open_Data">Open Data</a> :-)
</p>

2 changes: 1 addition & 1 deletion app/views/site/index.erb
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<input type="text" id="city2" name="city2" />
</fieldset>

<p>
<p class="ejemplos">
Ejemplos:
<%= link_to "Madrid versus Ámsterdam", '/madrid-versus-amsterdam' %>,
<%= link_to "Barcelona versus Berlín", '/barcelona-versus-berlin' %>
Expand Down
1 change: 1 addition & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
ActionController::Routing::Routes.draw do |map|

map.root :controller => 'site', :action => 'index'
map.about '/about', :controller => 'site', :action => 'about'

map.resources :cities, :as => 'ciudades'

Expand Down
51 changes: 48 additions & 3 deletions lib/tasks/modal_kombat.rake
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@ require 'fastercsv'
namespace :modal_kombat do
desc "Importar todos los datos"
task :load_data => :environment do
STDOUT.sync = true
Rake::Task["modal_kombat:load_icity"].invoke
Rake::Task["modal_kombat:load_ikey"].invoke
Rake::Task["modal_kombat:geocode"].invoke
# Rake::Task["modal_kombat:geocode"].invoke
end

desc "Importar ficheros de índices extendidos (la mayor parte de datos)"
task :load_icity => :environment do
STDOUT.sync = true
puts 'Cargando icity...'
Dir[RAILS_ROOT+'/db/data/*.csv'].each do |csv_file|
FasterCSV.open(csv_file).each do |row|
next unless row[0].is_a?(String) and row[2] != 'CITIES_LAB'
next unless row[0].is_a?(String) and !row[2].nil? and row[2] != 'CITIES_LAB'
city = City.find_or_create_by_name row[2]
year = row[0].split('_')[1]
next unless year.to_i > 1900
Expand All @@ -35,11 +35,41 @@ namespace :modal_kombat do

desc "Importar datos de índices principales, para completar"
task :load_ikey => :environment do
STDOUT.sync = true
# La MIERDA de aplicación de la que me descargo los datos ha tenido este
# detalle
renaming = {
'M?nchen' => 'München',
'Kernel K?benhavn' => 'Kernel Kobenhavn',
'Besan?on' => 'Besançon',
'Ume?'=> 'Umeå',
'Lens - Li?vin'=> 'Lens-Liévin',
'Trenc?n'=> 'Trenčan',
'Gij?n'=>'Gijón',
'M?nchengladbach'=> 'Mönchengladbach',
'Sz?kesfeh?rv?r'=> 'Szekesfehervar',
'Kecskem?t'=> 'Kecskemét',
'Pamplona/Iru?a'=> 'Pamplona/Iruña',
'Orl?ans'=> 'Orleans',
'N?rnberg'=> 'Nürnberg',
'G?teborg'=> 'Göteborg',
'Set?bal'=> 'Setúbal',
'G?ttingen'=> 'Göttingen',
'M?lheim a.d.Ruhr'=> 'Mülheim a.d.Ruhr',
'K?benhavn'=> 'Copenhagen',
'Link?ping'=> 'Linköping',
'D?sseldorf'=> 'Düsseldorf',
'Logro?o'=> 'Logroño',
'J?nk?ping'=> 'Jönköping'
}

puts 'Cargando ikey...'
Dir[RAILS_ROOT+'/db/data/ikey/*.csv'].each do |csv_file|
FasterCSV.open(csv_file).each do |row|
next unless row[0].is_a?(String) and row[2] != 'CITIES_LAB'
city = City.find_by_name row[2]
next unless city
city.update_attribute('name', renaming[city.name]) unless renaming[city.name].blank?
year = row[0].split('_')[1]
next unless year.to_i > 1900
dataset = city.datasets.find_or_create_by_year year
Expand All @@ -53,10 +83,25 @@ namespace :modal_kombat do

desc "Geolocalización de cada ciudad, por limpiar nombres y obtener países"
task :geocode => :environment do
STDOUT.sync = true
puts 'Geolocalizando ciudades...'
City.all.each do |city|
city.geocode!
print '.'
end
end

desc "Limpiar datasets chungos"
task :clean => :environment do
STDOUT.sync = true
puts 'Limpiando...'
modes = ['pedestrian_share', 'motorized_share', 'public_transport_share', 'bike_share']
Dataset.all.each do |data|
modes.each do |m|
data.destroy if eval("data.#{m}").nil?
end
end

City.all.each { |c| c.destroy if c.datasets.blank? }
end
end
21 changes: 21 additions & 0 deletions public/stylesheets/default.css
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,24 @@ table.datatable td.even { background:#222; }

#city #container { float:left; width:48%; }
#city #table { float:right; width:48%; }


#posiciones h2 {
font-size: 2em;
margin: 0 0 .7em 0;
padding-top: 1em;
}

#posiciones p {
font-size: 1.5em;
margin: 0 0 0 1em;
}

#city #table p {
font-size: 1.4em;
margin-top: .5em;
}

form#combat.estirar p.ejemplos {
font-size: 1.3em;
}

0 comments on commit 64bc068

Please sign in to comment.