Archive for the ‘Ruby On Rails’ Category

Zed Shaw - Exposing the ‘Ghetto’

Posted on January 3rd, 2008 in Open Source, Ruby, Ruby On Rails | Comments

Before I begin, I just want to wish everyone a Happy New Year! May 2008 bring happiness, peace and prosperity to all.

I’ve been keeping myself very busy lately with RSpec and Behavior-Driven Development, basically learning the ropes and how all the pieces fit together. For now, I’m totally enjoying it. But more on that in a future post.

Now, I know that everyone who read Zed Shaw’s rant towards most of the Ruby and Rails communities will have an opinion on this. But I’ll give my own thoughts on it. All I hope is that someone doesn’t read this and think “Who the hell is this guy to give an opinion?” I might not be a ’somebody’ in the Ruby or Rails communities at the moment, but I would really like to be part of those communities sometimes in the near future.

Upon first glance, Zed’s rant seems like a completely immature piece, just looking to damage the reputations of certainl people and companies. But if you read closely, ignoring the unprofessional language scattered throughout the text, there’s a whole lot of valid thoughts and reasoning to this entire rant.

Most of his attacks are aimed at two people: Kevin Clark and Dave Thomas. Kevin Clark has been a pretty big part of the Rails community, regularly contributing code and such, and Dave Thomas of course is the author of possibly the most well-known Ruby and Rails books in the market. His story on Kevin is that they possibly never got along and clashed multiple times, while the story on Dave is that supposedly Zed had a fix for a pretty serious bug in Ruby, yet Dave and others ‘threatened’ Zed to not release it. For what reason, it’s not clear in the rant. Now, about these allegations, I don’t know whether they’re true or not (there’s always two sides to a story). But from my own views, I think any environment has these types of problems all the time. My own workplace can be used as personal experience on these manners. There’s always someone who wants to be smarter and better than you, and for some unknown reason they go out of their way to make sure they come out looking better than you can. It’s stupid, but it’s just human nature, I guess. I bet almost any other open-source community is the same.

He also goes on to write about Thoughtworks, a software consulting company that jumped on the Rails bandwagon a while back. Zed’s beef with them is the fact that they charge a shitload of cash while providing not-so-great work in return. Isn’t this is the case with almost all software consultancy places? I can name a few off the top of my head here in Puerto Rico. In fact, all you need to do is go to a website one of these ‘expert software consultants’ made, look at how the site is built, and anyone with an eye for software development standard practices can name a dozen things they would change immediately. This is no surprise here.

I do commend Zed for not making this a 100% negative jab towards Ruby and Rails. He included some people who he knows and have helped him out or were unlike those who he vilified before. Like I said, all communities have their share of bad apples, mostly people who want to be most widely known at your own expense. So the fact that he names some people who were cool to him shows that.

I’ve read a lot of other blogs where people are dismissing Zed for the way he expressed his views, that he burned his bridges and what not. But that’s what he apparently wanted. He said he’s not happy being part of the Rails community, so he wants out. This is his way of getting out. Now, I may not agree with the way he did this at all. You never know when you need to cross a bridge you burned in the past, after all. But being in the position he was, seeing and knowing a lot of things that went down, he has a valid opinion, and he’s simply entitled to it.

I think Zed partly wrote this rant not to bash everyone associated to Ruby or Rails, but to try and help out, in his own way. He knows a lot more about the community than most of us will probably ever know. So hopefully some good comes out of him exposing some dirty details on how the Ruby and Rails world is run. In the end, it simply boils down to this: It’s one man’s opinion. No matter how important he is (or rather, was) to the Rails world, one man isn’t enough to kill it, in my opinion.

Zed, if you miraculously read this, best of luck to you in the future, buddy. Hope the rant was worth it!

At the speed of Rails

Posted on December 20th, 2007 in Open Source, Programming, Ruby, Ruby On Rails | Comments

I was going to write a small post about Rails and its brand-spankin’ new release, known at version 2.0. But in the time it took to write this, the Rails community not only released Rails 2.0, but also Rails 2.0.1 (thanks to a small error in the original 2.0 release) and 2.0.2 (bug fixes and some nice changes included) were released in short order. That’s part of what I love about the entire Ruby and Rails community: You need to be on your toes and always up-to-date. It may be a pain at times, especially when there’s barely any time for one to do anything at all. But it’s just a blast, and I’m enjoying the ride.

I’ve been using the new Rails features for the past five months now, thanks to access to the Rails Edge code. I really like the direction the framework is taking. RESTful routing is now the norm, multiple views of the same chunk of data are now a breeze, huge security benefits straight out of the box… There’s just too many good things Rails 2.0 has brought out. And the upcoming release of Ruby 1.9 (and its promised speedups) have me anxiously awaiting its arrival. In fact, I’m thinking of porting my Puerto Rican Rails site, RailsPR.com, from the “obsolete” Rails 1.2.3 to benefit from all the changes made by DHH and the rest of the Rails core team. Excellent job, guys. Here’s looking towards the bright, bright future of Ruby and Rails. I’m excited to be part of it.

I want everything!

Posted on October 12th, 2007 in Open Source, Programming, Ruby, Ruby On Rails, Software, Web Development | Comments

The past two weeks I’ve been totally separated from all of my learning and reading processes I’ve established to myself, and I felt terrible for doing that. It’s not like I’ve been totally disconnected from everything. I’ve still read all my favorite programming-related blogs, as usual. Still, I haven’t just sat down to absorb everything or practice.

These past two days I decided to get back on track. However, I found myself with the same problem I’ve had for a while now. Whenever I sit down to learn something, I want to learn everything. I don’t mean “learn everything of something“. It’s more like “learn something from everything“.

For the past months, I’ve had a hundred different interests. I’m interested in learning Adobe AIR. Microsoft Silverlight sounds like something I could use in the future. I was sold on Test-Driven Development and ever started to adopt its practices to my daily usage, yet recently I’m liking the sound of Behavior-Driven Development more and more and would like to test that road. I want to learn other web frameworks in different programming languages, like Django and CakePHP. And of course, I’m still totally into Ruby and Rails.

I know a lot of people who don’t mind knowing about everything. But the deal is that by learning (or having the desire to learn) about so many things, you don’t fully learn it all. You only learn a bit about each thing, but never a whole lot. There simply isn’t enough time in the world to do so, especially with a full-time schedule. So to say it’s frustrating is an understatement to me.

One technique I’m finding useful to juggle these interests is to create a necessary project in your mind to learn along the way. This should keep your interests level high during the learning process, while making you stay focused with one or two things at a time. For example, my next project is a web application, where I’ll strictly try to use the practices of Behavior-Driven Development while learning to use RSpec. This way, I’ll be learning a lot of different, yet related, subjects at the same time. After this project is done, I’ll see where Adobe AIR has headed, since it’s still in Beta. If it still piques my interest, I’ll create a new project for one of my current needs, and learn from there.

Being in this world of programming and technology, where it seems like time is always on fast-forward, it can be tough to keep up with what you like. But at the same time, it’s just fun. Even though I get frustrated at times, I’m having a ball learning these things. I guess it all boils down to that for now.

RailsPR.com - A Ruby and Rails community for Puerto Rico

Posted on October 1st, 2007 in Open Source, Ruby, Ruby On Rails | Comments

Note: Unfortunately, I had to take this site offline, due to its inactivity, and due to the fact that I have moved to New York City. I had plans for this site to be a starting point for me to start my own Ruby and Rails User Group in Puerto Rico, but I obviously can’t do that now. Hopefully someone in the near future in Puerto Rico will want to do something similar.

Although I finished this project a while back, I hadn’t announced it anywhere, so here it is. I just finished RailsPR.com, a site which I hope generates some much needed attention to the Ruby programming language and Rails framework here in my native land of Puerto Rico.

The main reason I started this site is because the IT industry in Puerto Rico is currently just centered on Microsoft products. I’ve said in a previous post that I really don’t mind Microsoft, and I think some of their products are great. However, with so many stable and useful open-source alternatives in the market, from operating systems to programming languages, I don’t see why it should be this way.

I’ve been learning and using Ruby for most of this current year, along with Rails. And it still baffled me whenever I talk to other programmers, they don’t even know what Ruby is. They’re still stuck with the same Visual Basic teachings they had in college. There are even some still using COBOL.

So my mission with this site is to create a community where interested programmers from Puerto Rico can be together in one place, sharing their knowledge and experiences, which is really what open-source is all about. It would make me proud to have my site be one of the main reasons people got into Rails.

Capistrano - Like that person you hate, yet end up falling in love with

Posted on September 3rd, 2007 in Open Source, Ruby On Rails, Software | Comments

One of the reasons I went exploring into Rails was because of Capistrano, a utility that greatly helps deploying Rails sites into production servers, by automating many of the tedious setup steps needed to deploy new changes into production. I know I can’t be the only one who has once or twice pushed some new change into production, only to discover (by myself or an angry user) that I forgot to bring the database schema up-to-date as well. Capistrano (actually, migrations are the key component here) will never allow that to happen again.

In a nutshell, Capistrano does the following:

  • Logs into your server via SSH
  • It creates a directory structure that’s useful in case you want to rollback some bad code you mistakenly pushed unto the server
  • Uses Subversion (or other SCM) to checkout the latest code committed into the repository and downloads it
  • Automatically runs all migrations to make sure the database is up-to-date
  • Runs other scripts, like making sure your FastCGI processes are restarted and running correctly, or restarting your web server

After nearly finishing my first public Rails site (coming soon, I promise!), I wanted to learn how to use this tool by deploying the first version into my VPN space using Capistrano. I thought this would be a daunting task, and at the beginning it was thanks to some minor errors, but after that, it was total bliss. After a few hours of tweaking my settings, I finally got it to work, and all deployments from here on out should be as simple as writing cap deploy without and remorse.

I’m going to write how I set up my deployment environment, so if anyone has had similar problems to mine, they can hopefully get past them.

First off, let me write about my app and server environment:

  • Operating System: CentOS 4.5
  • Webserver: Lighttpd 1.4.15
  • Rails Version: 1.2.3
  • Mongrel: 1.0.1
  • Capistrano: 2.0.0

After installing Capistrano on my development computer (simply using gem install capistrano --include-dependencies), I was ready to “capify” my application. To create the files used for deployment, just issue capify . at the root directory of the Rails application. This creates two files: Capify, which points to the second file, config/deploy.rb, which is the actual deployment configuration file.

The configuration is pretty straight-forward. There are some default settings that can e easily changed to reflect your production server setup. I did just that, and that’s where the ‘gotchas’ started pouring in.

After I changed the default values to my own, I wanted to set up the directory structure in my production server. To do that, simply run cap deploy:setup in the root directory of your application. That should prompt you for your SSH password to create all the directories needed in the directory specified in the deployment file (using the :deploy_to variable). However, when I did that, I got a nice error message: no such file to load — openssl.

After searching a few minutes in Google, I found my problem: I had compiled Ruby from source without the openssl-devel libraries installed in my system. Without the header files, Ruby compiled without OpenSSL support. So after installing the OpenSSL header files and recompiling Ruby (don’t forget to run make clean before recompiling), I was faced with another error message: It stated that my server didn’t exist. Then I remembered I’m running SSH in a non-standard port. Capistrano assumes it’s running on the default port, which is 22. After a few more minutes of searching, I found an option that needed to be added to the deployment file: ssh_options[:port] = xx, where xx is your SSH port number. After these changes, I was golden, as Capistrano asked for my SSH password.

After entering it in and seeing some progress in the directory creation process, I was faced with yet another error message, about a user not existing. I was assuming Capistrano was using the user name from my development box to log into the production server. In any case, this was fixed by adding another option in the deployment file: set :user, "production_user", where production_user is the user name with the appropriate permissions to create the directories and files in the production server. I ran cap deploy:setup once more, and all my directories were created. Success! Little did I know that would be only the first steps, and more troubles were looming ahead.

Once I verified the directory structure was created correctly on my production server, I went ahead and ran cap deploy:cold, which deploys my latest working version to the server, runs all migrations, updates all symlinks to the current code, and runs all remaining processes, like respawning all FastCGI processes, for the very first time. I once again ran into a small snag, as I was having permission problems running some scripts on the production server. After some more minutes of searching, I found that there’s a variable that needs to be set to make sure Capistrano runs the scripts as a specific user with adequate permissions. After adding set :runner, "production_user" (once again, where production_user is the user with the correct permissions to run your application scripts) to my deployment file, I was able to pass the permission parts, but then I hit yet another snag: I was missing a file - script/spin.

I found it odd that Capistrano was looking for this file, as it’s not automatically generated either by Rails or Capistrano. But after calmly reading the Capistrano installation instructions (instead of skimming over most of it), I saw that this file is used to recreate (or create) the FastCGI processes in your production server, to ensure that the users will get served the latest version of your app. There are many different ways to set up your FastCGI processes, depending on what the web server you’ll use. Since I use Lighttpd, I’ll be writing about that here. But you can find tons of useful information on the Internet if you use Apache, nginx or any other web server.

To remedy this problem, all I needed to do was to create the script/spin file (with executable permissions - chmod 0755 script/spin) with the following line (where /root_of_app/ is the path you described in the set :deploy_to: variable in the deployment file):

/root_of_app/current/script/process/spawner -a 127.0.0.1 -i 3 -r 5

This script calls another script called spawner (included in current versions of Rails), which verifies if there are FastCGI processes currently running. If the processes exist, they’re recreated to show the new version of the app. If the processes don’t exist, they’re created. The -a switch indicates the IP address used to direct the FastCGI processes. If you don’t use this switch, it will default to 0.0.0.0, which was causing me problems later on. The -i switch tells the script to create three FastCGI processes in sequential ports. Finally, the -r switch tells the script to verify if these scripts are still active every five seconds. This makes sure that all processes are running smoothly. One switch I didn’t use was the -p switch. By default, the spawner script creates all FastCGI processes starting with port 8000. Using the -p switch, you can specify which is the first port. In my case, the three FastCGI processes are creates using ports 8000, 8001 and 8002. You can change that default if you wish.

After you create the spin script, you’ll need to commit it to your SCM so Capistrano can find it in the production server. Once committed, I re-ran the cap deploy:cold command, and I was greeted with success at the end. My latest version of the application code was sent to the server, all migrations ran, and the spin script created three FastCGI processes on my server. Awesome! My work here with Capistrano was done. After hating Capistrano for a good while, I fixed all the kinks and can now never live without it. I love you, Capistrano.

Feeling good for myself, I immediately fired up my browser and entered my site’s URL. Too bad only 500 - Internal Server Error appeared when I went to the site. Curious, I entered the URL once again, appending :8000 at the end of the URL, and lo-and-behold, the site appeared in all its glory. So the FastCGI processes created with Mongrel were working well. But my web server wasn’t transferring the requests to one of the three processes.

After looking around for more information, I saw how FastCGI processes, Mongrel and Lighttpd work together. In a nutshell, the request for the site is sent to Lighttpd, the web server. Lighty then needs to process this request and send it over to one of the FastCGI processes, which then displays the site on the user’s screen. Lighttpd is simply used in this case as a proxy, and lucky for me, it already has some basic proxy functionality built-in. However, it needs to send the the request somewhere. I saw some tutorials online that set this up, but it seemed to always send the request to only one of the three processes, which wasn’t efficient at all.

Here is where Pound comes into play. Pound is reverse-proxy and load balancer for web servers. Basically, it takes all requests from the web servers and passes it along to the processes running the site, making sure that all processes aren’t over-worked by load-balancing all requests. After installing Pound on my production server, I had to create a configuration file, by default stored in /usr/local/etc/pound.cfg (your location may vary, depending if you compiled and installed the program from source, or just installed a package):


ListenHTTP
Address 127.0.0.1
Port 7999
Service
HeadRequire "Host: .*site.com.*"
BackEnd
Address 127.0.0.1
Port 8000
End
BackEnd
Address 127.0.0.1
Port 8001
End
BackEnd
Address 127.0.0.1
Port 8002
End
End
End

This configuration will make Pound listen to the requests on port 7999 in the local machine (my production server), and forward the site’s requests to one of the three FastCGI processes created by the spawner script I talked about previously. I was surprised at how something so powerful could be easily implemented.

Now all I needed to do was to configure my web server to direct all site requests to Pound, which in turn passed them along to one of the three FastCGI processes. Skipping all the other default settings and changing all sensitive info that may compromise my site, here are my current Lighttpd settings for the site in question:


$HTTP["host"] =~ “(^|.)site.com$” {
server.document-root = “/home/production_user/railsapps/app_name/current/public”
server.error-handler-404 = “/dispatch.fcgi”
server.errorlog = “/var/log/lighttpd/site.error”
accesslog.filename = “/var/log/lighttpd/site.access”
proxy.server = ( “” => ( “site” => ( “host” => “127.0.0.1″ , “port” => 7999, “check-local” => “disable” )))
)

Make sure you load the mod_proxy server module so you can use the proxy.server option mentioned above.

Once I restarted Lighttpd, I entered my site’s URL, crossed my fingers, and… success! I finally had a working site, load-balanced and all. What set out to be a learning process in Capistrano in turn made me use load balancing techniques in my site, which was something I planned on doing, but on another day, thinking it was super-complicated.

From here on out, every time I make a change I want to push to my site, all I need to do is run cap deploy on my development box, and that’s it. Everything will be updated with a simple command. It’s truly worth the time I spent getting it to work. Now I will never have an angry user again because I forgot to update the database schema.

In all, I spent a few hours fixing all the small kinks I encountered along the way. But as all good things go, you need to bust your ass to get things working like you want to. I don’t mind at all, as I learned a whole lot in one day. I hope someone finds some solutions in this writeup.

In case you’re curious, here’s my deployment file, with all the sensitive info changed for obvious reasons:


# Application Name - Anything you want to describe your application
set :application, "app_name"
# The URL of your source code repository, pointing to the latest version
set :repository, "http://svn_repo/trunk"
# Set the user name to connect to the server via SSH
set :user, "production_user"
# Set the user name of the user with permissions to run the application scripts
set :runner, "production_user"
# Set the path where you want your application to be stored
set :deploy_to, "/home/production_user/railsapps/#{application}"
# Option to change the SSH port
ssh_options[:port] = xx
# The URL or IP Address where your application will be stored - Multiple sites can be specified
role :app, “xx.xx.xx.xx”
# The URL or IP Address where your application will be served - Multiple sites can be specified
role :web, “xx.xx.xx.xx”
# The URL or IP Address where your database lives - Multiple sites can be specified
role :db, “xx.xx.xx.xx”, :primary => true
# Task to restart the web server
task :restart_web_server, :roles => :web do
sudo “/etc/init.d/lighttpd restart”
end
# Restart the web server once the deployment is finished
after “deploy:start”, :restart_web_server

Rejection!

Posted on May 8th, 2007 in Ruby On Rails | Comments

It’s certainly been a very interesting week for me. First, I was infected with the dreaded Pink Eye early last week, which prompted me to stay indoors from Tuesday to Friday. I finally got completely cured on Sunday night. Too bad it was just in time for Monday morning, which can be dreadful, especially when I had tons of work waiting for me on my desk for the four days I was absent.

However, I didn’t mind that much, as I got to make a ton of advances with the task of migrating the company’s current inventory system to Ruby On Rails (more on that in a future post). I also took the time to send the ol’ resume to some companies (which shall remain nameless for the moment) in the U.S., particularly San Francisco. Surprisingly enough, I received two answers to initiate the interview process with them! For some reason, I wasn’t expecting it at all. It’s probably the fact that I thought most employers would don’t waste their time with local candidates (although I made sure to emphasize the fact that I’m planning to move soon). In any case, that was pretty damn exciting for me, and I’m still psyched because of the quick responses.

So I initialized the interview process with both companies. One company sent some questions, seemingly just to gauge my personality traits. Once I completed it, someone from the company actually took the time to schedule a phone conversation with me and talk about the position. That was a really great touch, and I don’t think companies looking to hire great talent do this enough. After the conversation, which got me even more interested in the position, I received a programming test. It was right up my alley, and best of all, as the company is a Ruby On Rails shop, I had a chance to show my up-and-coming Rails skills. It took about a single day to complete (Sunday). I’ve been waiting for a reply, but I feel really, really good about this opportunity.

The other company sent me a written exam, mostly consisting of questions that challenge your logical way of thinking which I had to complete and return in an hour. These types of exams have been made famous by companies like Google. I thought I did pretty well, although I have to admit the questions were pretty tough. Maybe I was too nervous. In any case, I sent the exam on Friday afternoon and waited.

This morning, I woke up and checked my E-Mail for any response. I saw an E-Mail from the company that sent the written exam (not the Rails program). My heart raced as I clicked the link. Then I saw the following words: “Unfortunately we feel that *the company* is not the right fit for you at this time.” Needless to say, it certainly wasn’t the best feeling in the world.

I don’t know why I wasn’t accepted, although maybe I didn’t complete the exam as well as I originally thought. However, I do thank the representative from the company for taking the time to send the test in the first place. I’m guessing that if the company didn’t think I was actually qualified by looking at my resume, they wouldn’t have taken the time to schedule the test.

After a few minutes of being sort of heart-broken, those feelings were quickly removed. Why? I now know that I can - and need - to do better every time out. And to tell you the truth, the rejection pretty much motivated me to keep on going forward with learning new things. In fact, I took half of my lunch hour just to keep on adding new stuff to the program I’m migrating to Rails. This kind of opened my eyes, and makes me want to be better, the best I can.

I’m not bitter at all with the rejection. As I said, I genuinely thank the company for the opportunity in the first place. In the future, I’ll thank them again, when I’m much, much better at what I do.

Digg API with Ruby (and Rails too!)

Posted on April 25th, 2007 in Programming, Ruby, Ruby On Rails, Software, Web Development | Comments

Note: This site has changed a lot over the last year. I’m not using Rails anymore on the site, so there’s no place where I’m currently using the Digg API. However, I’ll leave this post intact, as it might help others with something similar.

If any of you readers have come in through my main site lately, you should notice that I added a little something on the sidebar. One of my favorite time-wasting activities of the day is browsing Digg. I tell you, there should be some sort of “Diggers Anonymous” for us simple-minded folk who can’t stop from visiting the site for stories many times a day!

Anyway, they recently announced the release of the Digg API, to allow any user to access the stories on the site in any way, shape or form we desire. Now, I must say that I have no real use for this. Of course, being the geek I am, I just wanted to try it out and see how I could use a simple API using Ruby, for use on my Rails site (this one). This is also made in case anyone else wants to do the same. One note, however: I’m only a Ruby / Rails beginner. I’m sure there are much better and efficient ways to do this. Since I haven’t dabbled in this too much, and “it works on my machine“, I’ll leave it as it is for now.

Just for the record, the testing and development for this code was made on my computer running Ubuntu 7.04, along with Ruby 1.8.6 (compiled by myself, not downloaded from the Ubuntu repos), RubyGems 0.9.2 and Rails 1.2.3. It should work correctly with any fairly recent version of the software mentioned above.

The Digg API is rather simplistic right now. All you need is a simple request using a URL like this:

http://services.digg.com/stories?appkey=http%3A%2F%2Fdennmart.com&type=xml&count=5

In the example above, the API is called to the ‘http://services.digg.com’ server. The parameters afterwards (in this case, ‘/stories‘) is the request. You can add more parameters for a finer-grained search.

Once the request URL is complete, you need some additional actions to add as well. The ‘appkey‘ is required, but can be anything for now. Digg isn’t generating application keys (a la eBay or other external API’s), but an appkey is required for ’statistical purposes’, according to the documentation. The ‘type‘ is how the data is going to be returned to the app, and it can be either XML, Javascript, JSON or PHP. I use good ol’ XML for now, until I can actually play around further with the other response types. Finally, the ‘count’ action is to limit how many stories are returned. I’m only going over these options quickly, as the API documentation has much more information.

Once you figure out which request you want to make (using Mozilla Firefox can help greatly, as the XML response is nicely formatted), it’s a matter of getting that data into your Ruby or Rails app. Going back to the ol’ trusty Pickaxe book, I found a nice little module integrated in Ruby called open-uri. This module allows the Ruby application to open a URL (either http, https or ftp) and get the returned contents. To use this module, a simple line of code is needed:

require 'open-uri'

That should load your module correctly. Now it’s just a matter of having Ruby open the API connection and store its XML response in a variable:

response = open('http://services.digg.com/stories/popular?appkey=http%3A%2F%2Fdennmart.com&type=xml&count=5').read

The ‘open‘ function, well, opens the connection to the API, while the ‘read‘ method gets the data that’s returned from the URL. Like I said, rather simple.

However, I was getting timeout errors when calling the ‘open’ function. Strangely enough, the function worked fine when using any other URL. Upon further reading of the API documentation, I found this little tidbit:

“All API requests must include a User-Agent HTTP Header. A request without this header will receive no response.”

So, after that small mistake, I edited the request like so:

response = open('http://services.digg.com/stories/popular?appkey=http%3A%2F%2Fdennmart.com&type=xml&count=5', 'User-Agent' => 'Ruby/1.8.6').read

The ‘User-Agent‘ parameter can be anything. I just decided to use the Ruby version I have. Once I added that, I had my nice XML with the five most recent Digg stories that have been promoted to the front page.

After that, I needed to parse that XML. I searched around the Internet, and found a great little module called ‘XmlSimple‘. This module reads and writes XML, and formats it according to whatever’s needed. In my case, I needed to read the XML response. Just like the ‘open-url’ module previously, you need to load the ‘XmlSimple’ module as well, once installed (”gem install xml-simple“):

require 'xmlsimple'

I did run into some minor problems when loading this module. The Ruby interpreter cried out loud, saying it couldn’t load the module. How come? I verified that the gem was installed correctly, and it was. Then I realized that since this is a gem, I need to have ‘RubyGems‘ loaded before loading ‘xmlsimple’:

require 'rubygems'

I believe that Rails already loads the module for you. But if you’re testing this out on Ruby and not on Rails, you’ll need it.

Okay, once I did that, I was able to load the ‘xmlsimple’ module. Now I need it to parse the XML response that I stored in the aptly-named ‘response‘ variable. A simple line of code can convert the XML into a hash:

XmlSimple.xml_in(response)

That takes the entire XML string and puts it into a neatly organized hash. I really don’t need everything in the hash, just the story title, link and how many diggs the story has. So I just access those particular keys:

digg_hash = XmlSimple.xml_in(response)
story_title = digg_hash['story'][0]['title']
story_link = digg_hash['story'][0]['link']
story_diggs = digg_hash['story'][0]['diggs']

In the example above, the ‘story_title‘ variable has the most recent story title, the ‘story_link‘ is the link that takes you directly to the story, and the ‘story_diggs‘ has the current amount of diggs that story has. The number zero used in the array is the story number. If you want to get more than one, you’ll need to loop through the array and get the other stories.

The code I’m using on the main site right now is the following:

<%
  require 'open-uri'
  require 'rubygems'
  require 'xmlsimple'

  response = open('http://services.digg.com/stories/popular?appkey=http%3A%2F%2Fdennmart.com&type=xml&count=5', 'User-Agent' => 'Ruby/1.8.6').read
  articles = 0
  while articles < 5
%>

(Dugg <%= XmlSimple.xml_in(response)['story'][articles]['diggs'] %> times)
<% articles += 1 end %>

In all, this was rather simple, and I’m sure there will be a much more creative use for the Digg API soon. But for those who want to learn how to use it, or those who need a very simple approach, this works just fine. I’m interested in listening on how other people have put this to use. Hope this helps someone!

Rails Screencasts = The best learning tool on the Internet

Posted on April 16th, 2007 in Programming, Ruby On Rails | Comments

Well, it’s been a while since I last posted. Maybe it was due to the fact that I received so many damn spam comments that Akismet seemingly didn’t block. I’ll look into that when I have some free time to check it out. For now, I’ll just give a quick post on what’s on my mind.

Even though I haven’t been posting on this blog, it doesn’t mean I haven’t been occupied with my Rails learnings. I just discovered the wonderful new world of screencasts as a learning tool. If you don’t know what a screencast is, it’s basically a video tutorial. Instead of reading something off the Internet, where the instructions aren’t always crystal clear, a screencast shows you what to do, and how it’s supposed to work. I’ve found them to be an invaluable tool in my quest for Rails wisdom.

There are a couple of sites that offer Rails screencasts exclusively. The first site is Railscasts. This site is frequently updated with short screencasts about various Rails topics. I’ve noticed these videos are truly great for beginners, as most of the topics covered so far seem geared more towards people without much Rails experience. Even though the videos are normally short (about five minutes in length, maybe less, as an average), they’re packed with useful information that’ll help any beginner get a better grasp at certain Rails topics.

The other site I’ve visited is Peepcode. These people make high-quality and full-length screencasts (over an hour long!) for the low price of $9.00 for each video. Many may think “But why pay for screencasts that can be freely accessible from the other site?” There’s a very large distinction between the screencasts from both sites. While length is obviously the main factor, the material shown on Peepcode screencasts is much more extensive and covers absolutely all the bases. Many of the screencasts that are currently available for purchase on Peepcode are geared to more advanced users, though. But in all honesty, $9.00 is a very small price to pay, given what you learn.

So if you’re trying to learn Rails like myself, I’d suggest you head over to one of these site pronto. You’ll be amazed at the great work that’s put out on the Internet for the sake of teaching others. That’s the beauty of the Internet.

Too bad it can’t all be Rails

Posted on February 22nd, 2007 in Ruby On Rails, Software | Comments

I finally finished the minor remodeling of my personal page, as I transferred the old, plain HTML files to Ruby on Rails. It didn’t take too long, since the site is all static (for the time being). Just in case you’re wondering, I moved everything to Rails mostly because I was tired of having to make a change to a menu, and I had to change every single HTML file. Not anymore. Although this apparently is the only benefit I’ve gained, I’m planning on adding many more things in the future (using Rails, of course).

Anyway, I was explaining what I was doing to the website to a co-worker. Although he doesn’t understand much about programming, he did seem to understand the whole Rails thing. So he asked me if the blog was also made with Rails. I told him no, it was using Wordpress, which runs on PHP. SO his next question was a natural one: Why don’t you use a Rails blog?

I’m sure some people who visit this site will ask the same thing. I have a couple of answers to this. I had tried to use Typo previously on this site, but rapidly removed it and started using Wordpress. First off, the web hosting company I’m using isn’t the fastest or most reliable host around for Rails applications. So Typo felt damn slow, probably due to the amount of memory it needs to run. I know there’s other blogging software built on Rails, but I haven’t had time to review them thouroughly yet, and I don’t seem to think they’re good for what I want.

Besides the slow speed, Typo hasn’t been updated in quite a while. The last update was in August of last year. Now that normally wouldn’t be a problem. But I think that at the very rapid pace Rails is evolving, most Rails developers need to keep up with this pace. Granted, that’s not always possible. But with all the new additions Rails gets with each release, I’m sure Typo and other Rails software could greatly benefit from those changes.

So for the time being, I’ll stick with Wordpress. It’s relatively fast and stable, and very easy to manage. Can’t ask for more. Maybe in the future Typo will be updated, or I’ll switch hosting companies and find Typo to be great, or maybe there’s some blogging software out there built on Rails that can solve this minor dilemma for me. For now, it’s too bad all my site can’t be built on Rails.

Is Rails confusing?

Posted on February 18th, 2007 in Programming, Ruby On Rails, Web Development | Comments

I’ve been learning Rails with great success these past two weeks. I’ve learned so many things during this period, much more than I’ve learned in a similar time frame for other languages / technologies. While there is still much, much more to learn (and memorize), I’m very happy in the time I’m investing in Rails, and don’t mind spending most of my free time reading and coding.

However, something that has happened to me a couple of times is that I get confused with certain things. For example, last week, I was really confused when reading about how forms work in Rails, and how to save and edit records in a database. Basically, it all came down to its simplicity confusing the hell out of me. For example, to save a new user, the only line of code needed in the controller was User.new(params[:user]). After watching this work nicely, I was amazed, but at the same time confused. How did Rails know what to save and in which fields? Where’s the SQL code? After reading a bit more about the form_for and form element helpers, as well as reading the logs, I found out how Rails does this automatically. Really great stuff.

However, some further confusion happened while reading about the form helpers. There were similar tags for the same thing. For example, there’s a form_for helper, as well as a form_tag helper, which create the form in the web page. Same with the elements. The text_field and text_field_tag apparently did the same thing, albeit each had different parameters. So that caused a bit of confusion early on.

So, maybe my mind was just fatigued because of the week I had at work, or I didn’t read my book well, but this caused me to look around to better understand these tags and what each one did, and why two (or more) similar helpers did different things. Thankfully, I’m the type of person who needs to know how things work. I’m never satisfied if I use something and if it works, I never question it. It may be the inner hacker in me.