Posted: July 13th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, Rails | Tags: Open Source, Programming, Rails | No Comments »
Este es el primer post de una serie que he decidido comenzar titulada “Analizando commits de rails edge”. Aclaro que los post no van a tener orden alguno y que voy a comentar los que me llaman la atención a _mí_
.
En este caso el commit se trata de agregar a rails la nueva forma de interpolación de strings que trae ruby 1.9 ( la idea es que se pueda usar con versiones menores también), pueden ver el código en este archivo:
activesupport/lib/active_support/core_ext/string/interpolation.rb
Cómo uds sabrán en Ruby se pueden interpolar strings de la siguiente manera:
>>"%s, %s" % ["Masao", "Mutoh"]
=> "Masao, Mutoh"
Cómo lo explica el comentario en el código:
# call-seq:
# %(arg)
# %(hash)
#
# Format - Uses str as a format specification, and returns the result of applying it to arg.
# If the format specification contains more than one substitution, then arg must be
# an Array containing the values to be substituted. See Kernel::sprintf for details of the
# format string. This is the default behavior of the String class.
# * arg: an Array or other class except Hash.
# * Returns: formatted String
# Example:
# "%s, %s" % ["Masao", "Mutoh"]
#
# Also you can use a Hash as the "named argument". This is recommended way so translators
# can understand the meanings of the msgids easily.
# * hash: {:key1 => value1, :key2 => value2, ... }
# * Returns: formatted String
# Example:
# For strings.
# "%{firstname}, %{familyname}" % {:firstname => "Masao", :familyname => "Mutoh"}
#
# With field type to specify format such as d(decimal), f(float),...
# "%d, %.1f" % {:age => 10, :weight => 43.4}
Es decir que ahora podemos interpolar strings de la siguiente manera:
>> "%{firstname}, %{familyname}" % {:firstname => "Masao", :familyname => "Mutoh"}
ArgumentError: malformed format string - %{
from (irb):2:in `%'
from (irb):2
>>
Auuuchh! estoy probando con un irb con ruby 1.8.6, así que necesito requerir el archivo:
>> require 'activesupport/lib/active_support/core_ext/string/interpolation.rb'
=> true
>> "%{firstname}, %{familyname}" % {:firstname => "Masao", :familyname => "Mutoh"}
=> "Masao, Mutoh"
Ahora sí! podemos interpolar string nombrados pasando un hash como argumento, Hermoso!
Estuve mirando en los fuentes de Ruby 1.9 y no encuentro dónde está escrita esta nueva funcionalidad, el método que define la interpolación con”%” es rb_str_format_m y está en la línea número 1202 del archivo string.c en el trunk de ruby, pero sólo está la vieja forma de interpolación. Entonces dónde está ? Alguien sabe?
Es más hice esta prueba:
$ irb1.9
require 'activesupport/lib/active_support/string/interpolation.rb'
=> true
irb(main):002:0> "%{firstname}, %{familyname}" % {:firstname => "Masao", :familyname => "Mutoh"}
ArgumentError: malformed format string - %{
from (irb):2:in `%'
from (irb):2
from /usr/bin/irb1.9:12:in `'
Y la versión que tengo de ruby 1.9 es:
ruby 1.9.0 (2008-06-20 revision 17482) [i486-linux]
Un poco vieja, probemos con ruby 1.9 compilado desde trunk
ruby 1.9.2dev (2009-07-11 trunk 24027) [i686-linux]
./ruby -e 'puts "%{firstname}, %{familyname}" % {:firstname => "Masao", :familyname => "Mutoh"}'
Masao, Mutoh
Funcionó! entonces en algún lugar tiene que estar.

(Via Gastón Ramos – Ruby, Rails….) Original Link: Rails edge, Ruby 1.9 style String interpolation support
Posted: July 13th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, Rails | Tags: how-to, Open Source, Programming, Rails, rake | No Comments »
Estoy terminando de hacer una migration a Rails 2.3 de la
app con la que estoy trabajando, resulta que me encontré con el siguiente tema:
Luego de instalar rails y migrar la app, llegó el momento de hacer un deploy a
staging, entonces me econtré con el siguiente error:
undefined method `reenable' for <Rake::Task db:schema:dump =>
[environment]>:Rake::Task
googleando un poco llegué a este link que dice que hay que instalar
la nueva versión de rake, investigando un poco más, llegué a este PATCH
que hace uso del método Rake::Task#reenable, el caso es que este método
se agrega e con la versión de rake 0.8.2 y como el pibe dice en el comentario
del patch, no hay problemas por que rails 2.3 require rake 0.8.3…. pero
que pasa cuando:
1- Instalo rails 2.3
2- Hago un ‘rake rails:freeze’
3- hago ‘cap staging deploy:migrations’
Y no tengo rails 2.3 instalado en el server y por eso justamente hice un freeze.
Si leemos la task que arma las dependencias de rails:
s.add_dependency('rake', '>= 0.8.3')
s.add_dependency('activesupport', '= 3.0.pre' + PKG_BUILD)
s.add_dependency('activerecord', '= 3.0.pre' + PKG_BUILD)
s.add_dependency('actionpack', '= 3.0.pre' + PKG_BUILD)
s.add_dependency('actionmailer', '= 3.0.pre' + PKG_BUILD)
s.add_dependency('activeresource', '= 3.0.pre' + PKG_BUILD)
uando hacemos el freeze nos copia todas estas cosas menos el rake,
lo cual parece razonable. Pero creo debería agregar en config/environment.rb
config.gem “rake”, :version => ‘0.8.3′
Que opinan uds?

(Via Gastón Ramos – Ruby, Rails….) Original Link: Rails 2.3, rake y reenable method
Posted: July 7th, 2009 | Author: FreedomCoder | Filed under: Rails, SQL, how-to | Tags: how-to, Rails, sqlite3 | 1 Comment »
A few folks asked this over the past weeks, and since I released preview1 version of RubyInstaller, wouldn’t be awesome I write a guide for it?
So, here we go
First, Getting Ruby
Please download from here one of the preview1 installers for Ruby.
For this demonstration, I’m going to use Ruby 1.9.1-p129. Downloaded, executed and installed to it’s default location C:\Ruby19
Now, start a Command prompt with Ruby (under start menu, inside Ruby 1.9.1-p129).

Getting SQLite3
As you may know, Windows do not came out of the box with libraries like SQLite3. For this, we are going to download it from Internet.
Going to SQLite downloads, under Precompiled binaries for Windows, download sqlitedll-3_6_16.zip and sqlite-3_6_16.zip. Those two packages contains the DLL (sqlite3.dll) and the command line executable for SQLite (sqlite3.exe).
Please extract those contents inside C:\Ruby19\bin
Now, let’s get the Ruby bindings for SQLite3
Getting SQLite3/Ruby bindings
As you may know, the preferred way to distribute Ruby libraries is using Gems. Users on other platforms usually compile themselves these components, using the mechanisms provided by the operating system distribution.
We are going to avoid the compilation process using pre-compiled binaries that has been cooked for us.
So, back to the Command Prompt with Ruby, let’s install the sqlite3 bindings:
gem install sqlite3-ruby --source http://gems.rubyinstaller.org
Adding --source help us indicate a non-standard location from where gems are going to be installed. RubyInstaller team has built and packaged special versions of these gems that we hope get published soon into RubyForge, the official place for gem distribution.
Once installed, you should see something like this at the screen:
Successfully installed sqlite3-ruby-1.2.4.1-x86-mingw32
1 gem installed
These special version of the gem are fat binaries, which means these can be safely installed on Ruby 1.8.6 or 1.9.1.
Getting Rails
Now it’s time to install and build a Rails application. First, let’s install the rails gem:
gem install rails
That command is going to take a bit, since is a 2MB or so download, and will install several of the Rails dependencies (ActiveRecord, ActionPack, ActiveSupport, etc). You should expect similar output to this:
Successfully installed activesupport-2.3.2
Successfully installed activerecord-2.3.2
Successfully installed actionpack-2.3.2
Successfully installed actionmailer-2.3.2
Successfully installed activeresource-2.3.2
Successfully installed rails-2.3.2
6 gems installed
Let’s build our application now.
Creating a Rails application.
Let’s call the application railsapp
rails railsapp
An excerpt of the output you should get:
create
create app/controllers
create app/helpers
create app/models
create app/views/layouts
create config/environments
create config/initializers
create config/locales
create db
...
Rails 2.3.2 defaults it’s database format to SQLite3, so there is no need for us to tweak anything.
Checking if everything is ok, using script\about:
cd railsapp
ruby script\about
And the output should be something like this:
About your application's environment
Ruby version 1.9.1 (i386-mingw32)
RubyGems version 1.3.4
Rack version 1.0 bundled
Rails version 2.3.2
Active Record version 2.3.2
Action Pack version 2.3.2
Active Resource version 2.3.2
Action Mailer version 2.3.2
Active Support version 2.3.2
Application root C:/Users/Luis/railsapp
Environment development
Database adapter sqlite3
Database schema version 0
Now, it’s up to you create your models, controllers and everything.
Some notes and considerations.
At the time of this writing, Mongrel has not been updated to build and install properly either on 1.9 or MinGW versions of Ruby.
As part of Mongrel development team, I’m going to work on a solution for this in the upcoming days.
If you find something wrong with the Ruby Installer, please report here, but issues with your code, Rails or other are not responsability of RubyInstaller.
The binary gems provided at gems.rubyinstaller.org are based on our forks of sqlite3-ruby, which can be cloned and explored here at GitHub.
Keep in mind that some gems would not work under Ruby 1.9, or you will need a compiler (DevKit) for it. See previous post with details how to get those from our download page.
(Via DEV_MEM.dump_to(:blog) – Multimedia systems blog.) Original Link: RubyInstaller: Getting Started with Rails and SQLite3
Posted: July 7th, 2009 | Author: FreedomCoder | Filed under: Rails, SQL, how-to | Tags: how-to, msyql, Rails | No Comments »
This is a follow up instruction set from previous post, but this time, using MySQL
Getting Ruby
These steps are the same for Ruby 1.9 or Ruby 1.8, please feel free to download the installer from here
For this guide I’m going to use Ruby 1.9.1-p129, since it the coolest new version that all the guys are playing with
Now, start a Command prompt with Ruby (under start menu, inside Ruby 1.9.1-p129).

Getting the right MySQL version
While building the MySQL/Ruby bindings, we found that mixing versions of the bindings with different versions of MySQL installations ended on undesired results (abnormal program termination, weird errors, etc.)
For this guide, and because we are going to use binary gems, we are going to stick to MySQL version 5.0.83.
Now is time to download MySQL. For this guide, I’m going to install the essentials version, which contains only MySQL and command line tools, no Query Builder or any other administrative tool.
Please go to this page and download Windows Essentials (x86). Once downloaded you will end with mysql-essential-5.0.83-win32.msi file. Execute it and install with defaults.
Configure MySQL
If you’re an advanced and savvy MySQL user, you can skip the following steps. For the sake of this guide, I’m going to list the simple options you must follow when installing it.
Once you installed MySQL, the installer should have started the Configuration Wizard page.
Inside of it, please apply the following options:
| Option/Screen |
Value |
| Configuration Type |
Detailed configuration |
| Server type |
Developer Machine |
| Database usage |
Transactional Database only |
| InnoDB datafile |
Your option or leave defaults |
| Number of connections |
Decision Support |
| Networking options |
Check Add firewall exceptions |
| Character set |
Best support for Multilingualism (UTF8) |
| Windows Options |
Add to PATH if you want mysql available on every prompt |
| Security Options |
Uncheck if you want root password be blank |
Once done with all this, on the summary screen, please click Execute to complete the configuration of MySQL Server.
Under some system, starting of MySQL server will fail during this wizard, but don’t be afraid, most of the times, this can be safely ignored.
To check everything was properly installed, please go to the Start Menu, and inside MySQL Server 5.0, click on MySQL Command Line Client
If you changed the root password, or, like me, leaved it unchecked, you can simply press enter when asked for the password and see that the server is running!

If you decided to add MySQL to the PATH, you will require to restart your computer so the PATH change is available to the system.
If you decided not to add MySQL to the PATH, please go, with Explorer to the location where you installed MySQL Server and copy libmySQL.dll into C:\Ruby19\bin
In my case, I found this file in C:\Program Files\MySQL\MySQL Server 5.0\bin
Now, it is time to install the bindings.
Getting MySQL/Ruby
For this version of Ruby, there is no official binary gems for both Ruby 1.8 and 1.9. So we are going to install the specially built version from RubyInstaller gems repository.
At the Command Prompt with Ruby, please enter the following command:
gem install mysql --source http://gems.rubyinstaller.org
This is going to install the special version of MySQL bindings. This version works with Ruby 1.8 and 1.9, since bundles fat binaries. You should expect a similar output like this:
Successfully installed mysql-2.8.1.1-x86-mingw32
1 gem installed
Getting Rails
Now is time to install Rails and build our application. At the same command prompt, please enter the following command:
gem install rails
This is going to take a bit, since Rails and it’s dependencies takes around 2MB or so, and need to be downloaded and installed.
Once done, expect see at the screen something like this:
Successfully installed activesupport-2.3.2
Successfully installed activerecord-2.3.2
Successfully installed actionpack-2.3.2
Successfully installed actionmailer-2.3.2
Successfully installed activeresource-2.3.2
Successfully installed rails-2.3.2
6 gems installed
Creating a Rails application
Let’s name our application mysqlapp
rails mysqlapp --database=mysql
The --database option indicates to Rails that we want to use MySQL instead of the default database adapter (SQLite3).
Rails will output a lot of lines when creating your application structure, just an excerpt of what to see:
...
create config/database.yml
create config/routes.rb
create config/locales/en.yml
create config/initializers/backtrace_silencers.rb
create config/initializers/inflections.rb
create config/initializers/mime_types.rb
create config/initializers/new_rails_defaults.rb
create config/initializers/session_store.rb
create config/environment.rb
...
Configuring our Database
Now Rails have configured for us the name of the database we want to use, and you can verify it in config\database.yml
Rails will try to connect to mysqlapp_development, but that database do not exist in our fresh new MySQL server.
So, let’s create it:
cd mysqlapp
rake db:create
Just that, simple db:create is going to connect to our MySQL server, and create the database for us.
Keep in mind that if you changed root password or want to use other MySQL user to connect to the database, you need to edit database.yml to reflect those changes.
Let’s verify that everything is in place, using the following command:
About your application's environment
Ruby version 1.9.1 (i386-mingw32)
RubyGems version 1.3.4
Rack version 1.0 bundled
Rails version 2.3.2
Active Record version 2.3.2
Action Pack version 2.3.2
Active Resource version 2.3.2
Action Mailer version 2.3.2
Active Support version 2.3.2
Application root C:/Users/Luis/mysqlapp
Environment development
Database adapter mysql
Database schema version 0
Now is up to you to create your models, controllers and views!
Some notes and considerations
On other post I’m going to guide you with steps on building the bindings against MySQL 5.1.36, since you will need to install the Ruby Development Kit and the development headers for MySQL.
If you find something wrong with the Ruby Installer, please report it here, but issues with your code, Rails or other are not responsability of RubyInstaller.
The binary gems provided at gems.rubyinstaller.org are based on our forks of mysql bindings, which can be cloned and explored here at GitHub.
Keep in mind that some gems would not work under Ruby 1.9, or you will need a compiler (DevKit) for it. See previous post with details how to get those from our download page.
(Via DEV_MEM.dump_to(:blog) – Multimedia systems blog.) Original Link: RubyInstaller: Getting Started with Rails and MySQL
Posted: June 13th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, Rails | Tags: Google, Open Source, Programming, Rails, search | No Comments »
web_search_plugin es un nuevo plugin de Rails que hice, para poder obtener los resultados de una determinada consulta en google y mostrarla en tu sitio. Hasta el momento solo realiza búsquedas en Google, a futuro lo voy a integrar con Yahoo y Live.
Instalar web_search_plugin
# cd myapprails
# ruby script/plugin install git@github.com:chebyte/web_search_plugin.git
Uso
Como ejemplo, tenemos el modelo #link.rb
class Link < ActiveRecord::Base
include Chebyte::WebSearch
web_search
end
Ahora para obtener los resultados solo debemos llamar al método search_web
Link.google_search(:query => "tuquito")
esto nos devolveria
=> #<Google::Response:0xb734d3cc @results=[{:domain=>"www.tuquito.org.ar", :content=>"Proyecto Linux de Tucumán, datos y temas relacionados al proyecto, foros y ayuda para usuarios de la distribución y descargas.", :title=>"Tuquito 3", :cache_url=>"http://www.google.com/search?q=cache:4NZXKc3gQA8J:www.tuquito.org.ar", :url=>"http://www.tuquito.org.ar/"}, {:domain=>"en.wikipedia.org", :content=>"Oct 11, 2008 ... Tuquito is a Debian-based operating system created in Tucumán, Argentina, by Ignacio Díaz, Chris Arenas and Mauro Torres, students of The ...", :title=>"Tuquito - Wikipedia, the free encyclopedia", :cache_url=>"http://www.google.com/search?q=cache:a1xAEvHHujUJ:en.wikipedia.org", :url=>"http://en.wikipedia.org/wiki/Tuquito"}, {:domain=>"www.slideshare.net", :content=>"Tuquito 3 Nuevo Diseño En varios idiomas (Ingles,Portugues y Español) Interfaces mas intuitivas Optimizado para la conectividad(wifi, ...", :title=>"Tuquito 3", :cache_url=>"http://www.google.com/search?q=cache:T8VfO-4iyioJ:www.slideshare.net", :url=>"http://www.slideshare.net/chebyte/tuquito-3"}, {:domain=>"www.olpcnews.com", :content=>"OLPC Tuquito's team began to work at 1st January of 2007, with the knowledge acquisition about the project One Laptop Per Child and then with development ...", :title=>"OLPC Tuquito Project Progress in Argentina - OLPC News", :cache_url=>"http://www.google.com/search?q=cache:eoGfDNbaZ8kJ:www.olpcnews.com", :url=>"http://www.olpcnews.com/countries/argentina/olpc_tuquito_project_argentina.html"}], @status=200, @size=4, @query="tuquito">
El resultado es un simple objecto hash, algunos de los campos disponibles son
* title titulo del resultado
* url Url del resultado
* domain Root url del resultado
* content contenido
* cache_url Google cache url
(Via Chebyte’s Blog.) Original Link: Google Scrap con Rails
Posted: April 7th, 2009 | Author: FreedomCoder | Filed under: Rails, jobs | Tags: jobs, Programming, Rails | No Comments »
I’m looking for a few good folks to join my team. You need to be able to work on site in San Francisco, we can assist with moving expenses for the right candidate.
You would work with my team(currently 5 devs). We do no bs agile style development with pairing where appropriate and test infected mentality . generally we have a fun, tight team and get to work on some of the hardest and most rewarding areas of software development relevant today.
You would be on my team working on http://engineyard.com/solo and it’s successors as well as Engine Yard’s on premises infrastructure.
You would be working on/with the following ruby technologies:
Ruby
Merb
Rails
Sinatra
DataMapper
Nanite
Chef
Event Machine
Many others..
You would be working on the following problem domains:
Scalable Ruby Deployment Architectures
Scalable Cloud Computing Architectures
Scalable Database Architecture
Distributed Computing
Key Value Data Stores
Infrastructure automation
Cloud provider API's
Multi-Cloud portability
Monitoring and alerting systems
Security in the Cloud
Horizontally Scalable Architectures
Many other interesting areas of computing
Familiarity with the following tech is nice but not necessarily required if you can learn fast:
Gentoo Linux
Nginx
Apache
Monit
Daemontools
Mysql
Postgresql
Memcached
Passenger
Mongrel
Thin
SSL Certs
Iptables/Networking
Erlang
If you think you have the “right stuff” and you have the kick ass take names attitude then send a resume with a short intro about who you are and why you are the person we should hire.
ez@engineyard.com
(Via Brainspl.at.) Original Link: Engine Yard hiring developers to help build our cloud
Posted: April 3rd, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, Rails, github | Tags: Flash, github, Plugins, Programming, Rails, Ruby | No Comments »
En la última semana estuve trabajando en agregar nuevas funcionalidades a un sitio de un cliente y entre los pedidos estaba una especie de Fotoblog para los usuarios (y bue, hay que pagar las cuentas a fin de mes
).
La cosa salió rápido, usando Paperclip que guarda las imágenes que se suben, se muestra en orden, etc, nada del otro mundo. Pero hablando con el cliente surgió la idea de hacer que el usuario se pueda tomar una foto directamente desde la web usando su webcam, así que después de decir “si, se debe poder hacer” mentalmente me salió un “doh!, que dije!“. Lo último que se dijo en esa reunión fue “Lo quiero”
.
Ya había visto juegos flash que utilizan la webcam así que empecé por ahí, para ver como sacaban un frame del video, lo cual era muy fácil. Lo siguiente era serializarla. A falta de algo mejor hice un serializador de imágenes muy pedorro, pero que anda (aunque es lento), que envía por POST la información de cada pixel.
La parte de Ruby fue fácil y decidí encapsularla en un plugin de Rails para poder reutilizarlo luego o por si a alguien más le sirve
. Además se puede integrar con Paperclip o AttachmentFu para hacer la persistencia de la imagen en donde sea.
La única parte que usa Flash es el capturador de la cámara, porque otra no quedaba, pero luego el botón para tomar la foto y los eventos se manejan todo por Javascript.
El plugin tiene varios TODOs, pero por si a alguien le sirve está en github.
(Via El Futirifoken.) Original Link: Take A Photo – Fotos instantáneas desde tu web
Posted: March 26th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, Rails | Tags: GeoLocation, Open Source, Programming, Rails | Comments Off
Knowing the user location is useful not only for statics, but also, for example, to avoid that the same ip address votes twice or to allow that your site shows products dynamically in relation with the place where the user is and a lot of other applications.
The first task is to know the ip address of the user, to do this we can use a very helpful method of rails called remote_ip, this function is very smart, looks for in the headers HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR and REMOTE_ADDR and parse the value to figure out the ip address. So if we want to know the ip address we can use this:
@client_ip = request.remote_ip
If you are working in your local machine the remote_ip will be 127.0.0.1 and this address cannot be processed, then you have to write the following, instead the above code:
@client_ip = (RAILS_ENV == 'development') ? '201.231.22.125' : request.remote_ip
Once we have the ip address we have to figure out the place where the ip address is from, to do this we are going to use a free database of MaxMind, they offer geolocation databases, the free edition (GeoIpLite) is less accurate than the commercial version but it was enough for me, here is the link to the free binary database, I decompress the database in /opt/GeoIP/share/GeoIP/.
To work with the above database you have to install the C library geoip, I did this from the source but you can get it from synaptic, these are the commands that I used:
wget http://www.maxmind.com/download/geoip/api/c/GeoIP.tar.gztar -zxvf GeoIP.tar.gzcd GeoIP./configure --prefix=/opt/GeoIPmake && sudo make install
And to work from Ruby with this library I use geoip_city gem, to install it I used:
sudo gem install geoip_city -- --with-geoip-dir=/opt/GeoIP
Well we have everything installed, now we can test it from the Rails side, in the root project open a console and run the following:
script/console
>> require ‘geoip_city’
>> g = GeoIPCity::Database.new(’/opt/GeoIP/share/GeoIP/GeoLiteCity.dat’)
>> res = g.look_up(’201.231.22.125′)
=> {:latitude=>-33.13330078125, :country_code3=>”ARG”, :longitude=>-64.3499984741211, :city=>”Río Cuarto”, :country_name=>”Argentina”, :country_code=>”AR”, :region=>”05″}
If you get something like this you have everything working, but when I did my first test I got the following error message:
“libgeoip.so.1: cannot open shared object file: No such file or directory”
I solved it running: sudo ldconfig /etc/ld.so.conf
Once that we have everything working we can build our country method oracle, I did it in the application.rb file:
def get_country
@client_ip = request.remote_ip @client_ip = '201.231.22.125'
if session[:country].blank?
g = GeoIPCity::Database.new('/opt/GeoIP/share/GeoIP/GeoLiteCity.dat')
@user_location = g.look_up(@client_ip)
# if there isn't a country_code then the default country is USA
session[:country] = @user_location[:country_code] || 'US'
end
end
and “voila” you have in all the views and controllers the variable session[:country] that contains the current country location of the user, if you want you can be more accurate and ask for cities, lats, longs but I just neded the user country.
Well this was my first post, so I hope that this will be useful for somebody.
(Via Docta Ignorantia.) Original Link: How to know a user location with Rails
Posted: March 25th, 2009 | Author: FreedomCoder | Filed under: Open Source, Programming, Rails, github | Tags: github, Open Source, Programming, Rails | Comments Off
Jekyll is a simple static site generator created by Tom Preston-Werner that is used as the engine behind the well-known GitHub Pages.
I must admit that the first time I heard about this, the idea did not grab my attention at all. But after reading some inspiring blog posts about it, everything started to make sense and I decided to give it a try on my new blog, and so far, I like it.
Installing Jekyll
The easiest way to install Jekyll is via RubyGems:
$ sudo gem install mojombo-jekyll -s http://gems.github.com
Notice that Jekyll requires directory_watcher, liquid, open4 and maruku. They will be automatically installed by the gem install command.
Creating content
Basically, what Jekyll does is to take several .textile or .markdown files and translates them into html, optionally using layout templates to avoid duplicating the common areas of our blog on each post. So, all we need to do is place our own content files in the correct locations.
A typical Jekyll blog setup would be as follows:
- An
index.html file on the root directory that will serve as the home page of our blog.
- One or more template layouts in the
_layouts directory. These layouts can then be referenced from any other file by using the layout attribute in the YAML header. Also notice that layouts can be nested.
- One .textile or .markdown file for each post in the
_posts directory.
- One .textile or .markdown file for each draft in the
_drafts directory. Any posts in this directory will be ignored by Jekyll at generation time.
- One or more .textile or .markdown files in the
_includes directory. Any files located in this directory can be included into another file with the include tag.
For a starting point, you might want to take a look at Tom Preston-Werner’s TPW repository.
Generating the blog
Once that the basic layout and content of our blog was set up, we are ready for telling Jekyll to generate our site:
$ jekyll
If everything goes well, by now we should have our brand new Jekyll-powered blog generated on the _site directory.
We can also run Jekyll with the --server flag in order to test the generated site:
$ jekyll --server
This flag tells Jekyll to launch a WEBrick server instance. Now we can point our web browser to http://localhost:4000 and test the generated site locally.
Publishing everything
At this point, we can just ftp the contents of the _site directory to our web site and we’re done.
However, a much better solution would be to create a remote git repository and add some git hooks there that take care of generating the site for us each time we do a simple git push. That is exactly the setup I am using to maintain this blog, and I will be writing about it in a future post.
Conclusion
This solution is definitely not for everyone. But if you are a programmer, and especially if you spend most of your day working with a text editor and a terminal window opened, then you may find the combination of Jekyll, Git, and your editor of choice (vim, in my case, but Emacs, TextMate or any other would work just fine, of course) more appealing than any traditional blog software.
(Via matflores.com.) Original Link: Getting started with Jekyll
Posted: March 25th, 2009 | Author: FreedomCoder | Filed under: ActiveRecord, Open Source, Programming, Rails | Tags: ActiveRecord, Open Source, Programming, Rails | Comments Off
Según se vaya avanzando en un proyecto, es posible que nos veamos en la necesidad de encotrar los registros vecinos para el que estemos utilizando en un momento dado. De este modo, por ejemplo si uno esta posicionado en un registro y desea obtener el siguiente, tener algo como “next” o “previous” sería muy útil.
Acts_as_ordered es un plugin interesante para obtener los registros previos o siguientes a uno determinado.Es muy versatil y potente. Se puede descargar de aquí.
Para mi cuestiones particulares, lo resolví a lo bestia, incluyendo estos dos métodos en la clase que los requería.
-
def self.previous id
-
prev_id= self.minimum(:id, :conditions => ['id > ?', id])
-
self.find(prev_id)
-
end
-
-
def self.next id
-
next_id=self.maximum(:id, :conditions => ['id < ?', id])
-
self.find(next_id)
-
end
Saludos
Inspirado de un reply en Duane’s Brain
leer más
(Via Rodolinux – Rodolinux’s Playground.) Original Link: Obtener registros previos/siguientes con ActiveRecord