Modulor. Custom Software Solutions.
Facebook | Twitter | LinkedIn
Posted by: Serguei on January 14, 2011
Category: Ruby on Rails
Just found this Ruby Quicktip for getting a random element from an array. There are two ways you can do this.

Given an array @array

@array = [1,2,3,4,5]

You can obtain a random element from the array with the 'choice' method:

=> 3

You can also do it with the 'sample' method

=> 2

With the 'sample' method you can specify the number of random elements you want:


=> [4,1]

Happy coding.
Facebook | Twitter | LinkedIn
Posted by: Gustavo on January 12, 2011
Category: Ruby on Rails
Some sites with continuous feed of updates will require RSS feeds in order for them to become more accessible and allow for content to be easily redistributed.

We can create an RSS feed easily with Ruby on Rails. You just need to follow the next steps:

1. Create an action in your controller for the RSS feed.

def rss
@noticias = Noticia.find(:all)
render :layout => false
response.headers["Content-Type"] = "application/xml; charset=utf-8"

2. Create a view, in this case rss.rxhml that will show the feed contents. It should look something like this:


xml.rss "version" => "2.0", "xmlns:dc" => "" do do

xml.title "Modulor News" url_for :only_path => false, :controller => 'home'
xml.description "Modulor Daily News"

@noticias.each do |noticia|
xml.item do
xml.title noticia.titulo url_for :only_path => false, :controller => 'home', :action => 'noticia', :id => noticia.permalink
xml.description noticia.descripcion
xml.guid url_for :only_path => false, :controller => 'home', :action => 'noticia', :id => noticia.permalink


3. If you want other websites of applications like Google Reader to auto-discover the feed, add the following html code to your views/layouts.

Just make sure your feed is valid and you're done.