Dear Railsists, Please Don’t be Obtrusive

obtrusive_or_not.png
Update: thanks to Jon Wood aka jellybob, a prototype demonstration has been added, which is even better than my original jQuery btw as it degrades gracefully. Check it out in the ‘prototype-unobtrusive’ directory.

I am guessing 9 out of 10 of you reading the title is prepared for yet-another Rails drama on some obtrusive community members, and because everyone is tired of Rails dramas, I am risking that some of you won’t care to read the article – but I couldn’t resist :-). Actually I’d like to talk about usage of (un)obtrusive Javascript – why is it a bad idea to be obtrusive, especially given that (as you will learn from the article) writing unobtrusive Javascript is not harder, and you get the warm, fuzzy feeling of writing nice and clean code!

The Drill

To demonstrate the differences, I’ll lead you through the creation of a quick AJAXy shout wall both the default/standard (and obtrusive) way, then do the same with unobtrusive Javascript to show you that contrary to the popular belief, you don’t need to memorize the “Tome of Javascript Black Magick Tricks” by heart, use obscure libraries or special coding techniques to achieve clean, unobtrusive code. The shout wall is simply a form for posting a new message, and a list of messages below it, like so:


shout_wall.png


(You can check out the code used in this post from it’s github repository).

The Standard Way

Note: If you’d like to follow along, please use the provided pastie links – do not try to cut & paste multiple lines from the page (single lines are OK), as it will be b0rk3d.

  1. Creating a new Rails application

    rails obtrusive-shout-wall
      
  2. Get into the Rails dir

    cd obtrusive-shout-wall
      
  3. Generate the resource message

      
    script/generate resource message
      
  4. Add this the following to the generated migration (some_timestamp_create_messages (Get it from pastie):

    t.string :author
    t.text :message	
    
  5. Run the migrations:

    rake db:migrate
    
  6. Because we want to view the messages in reverse order (newest one first), we add a default scope to the Message model (in message.rb):

        default_scope :order => 'created_at DESC'
    
  7. Create the application layout – create a new file in app/views/layouts called application.html.erb, and fill it with the following content (Get it from pastie):

    
      
        <%= stylesheet_link_tag "application" %>
    		<%= javascript_include_tag :defaults %>		
      
    	
        <%= yield %>
    	
    
    
  8. Create a file application.css and drop it into public/stylesheets. Add the following content (Get it from pastie):

    body {
    	background-color:#FFFFFF;
    	color:#333333;
    	font-family:"Lucida Grande",verdana,arial,helvetica,sans-serif;
    	margin:0 auto;
    	padding:0;
    	text-align:center;
    	width:960px;
    }
    
    #messages {
    	text-align: left;
    	margin-left: 80px;
    	margin-top: 50px;
    }
    
    #message-form {
    	text-align: left;
    }
    
    #message-form dl {
    	margin:10px 0 0 80px;
    }
    
    #message-form dd {
    color:#666666;
    font-size:11px;
    line-height:24px;
    margin:0 0 5px 80px;
    }
    
    #message-form dt {
    	float:left;
    	font-size:14px;
    	line-height:24px;
    	width:80px;
      text-align: left;	
    }
    
    #author {
      margin-right: 640px;
    }
    
    #message {
      width: 600px;
    	height: 200px;
      margin-right: 194px;
    }
    
    .message {
      margin-bottom: 20px;
    }
    
    .first_row {
      padding-bottom: 10px;
    }
    
    .message-meta {
    	font-size: 12px;
    }
    
    .author {
      color: #FF5050;
    	font-weight: bold;
    }
    
    .new-message-label {
      text-align: left;
      padding-top: 30px;
      margin-left: 80px;
    }
    
    #submit-button {
      float : right;
      margin-right: 195px;
      margin-top: 10px;
    }
    
  9. Create a new action, index in MessagesController (Get it from pastie):

    def index
      @messages = Message.all    
    end
    
  10. This goes into app/views/messages/index.html.erb (Get it from pastie):

    Enter new message!

    <% remote_form_for :message, :html => {:id => "message-form"} do |form| %>
    Author:
    <%= text_field_tag 'author' %>
    Message:
    <%= text_area_tag 'message' %>
    <%= submit_tag "Submit!", :id => "submit-button"%> <% end %>
    <%= render :partial => 'message', :collection => @messages %>

    We are showing the form for the messages and list the already exiting messages below the list.
    Note that we are using the _remote_form_for_ Rails helper to create an AJAXy form. This is already obtrusive, since if you observe the generated HTML, you will see that the form has an onsubmit parameter with some horribly looking code attached to it.:


    Obtrusive helper.png


    Sure, you can go ‘meh’ all the way, but slinging Javascript code all over the place is just as bad idea as writing inline CSS (or even worse, using HTML code for styling) or putting Rails code into views. It will work without any problems – but it’s just not the right way of doing things, especially if your code is going to hit a certain size.
  11. You probably noticed that we are rendering a message as a partial – so create a partial file app/views/messages/_message.html.erb with the following content (Get it from pastie):

    on <%= message.created_at.to_formatted_s(:long_ordinal) %>, <%= message.author %> said:
    <%= message.message %>
  12. We need a ‘create’ action in MessagesController in order to process the form submission (Get it from pastie):

    def create
      @message = Message.create(:author => params[:author], :message => params[:message])
    end
    
  13. And obviously we’ll need to render something to respond to the create action. Using the standard Rails way, RJS, we might come up with something like this (in app/views/messages/create.js.rjs – Get it from pastie):

    page.insert_html :top, "messages", :partial => 'message', :object => @message
    page.visual_effect  :highlight, "message-#{@message.id}"
    

    Here we insert the “messages” partial, using the just created @message, and throw a splash of yellow fade into the mix for good measure. Easy peasy.

  14. We are done! Fire up script/server, hit localhost:3000/messages and voila!

The Good Way

Here I am presenting only the steps that are different from the above – i.e. if step 3 is skipped, use the one from above.

  1. Creating a new Rails application

      rails unobtrusive-shout-wall
      
  2. Get into the Rails dir

    cd unobtrusive-shout-wall
      
  3. Same as above
  4. Same as above
  5. Same as above
  6. Same as above
  7. Since we are going to use jQuery (unobtrusiveness is *not* a property of jQuery, you can be just as unobtrusive with Prorotype – but I switched to jQuery just before learning how, and now I am lazy to go back check out how in the ‘prototype unobtrusive’ directory in the github repository), you have to download jQuery with some basic effects, as well as an AJAX form handling library (still from the directory unobtrusive-shout-wall – Get it from pastie):
  8. curl http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js > public/javascripts/jquery.js
    curl http://www.malsup.com/jquery/form/jquery.form.js?2.28 > public/javascripts/jquery-form.js
    curl http://view.jquery.com/tags/ui/latest/ui/effects.core.js > public/javascripts/effects.core.js
    curl http://view.jquery.com/tags/ui/latest/ui/effects.highlight.js > public/javascripts/effects.highlight.js
    

    and replace

    <%= javascript_include_tag :defaults %>
    

    with

    <%= javascript_include_tag 'jquery' %>		
    <%= javascript_include_tag 'jquery-form' %>
    <%= javascript_include_tag 'application' %>
    <%= javascript_include_tag 'effects.core' %>
    <%= javascript_include_tag 'effects.highlight' %>		
    

    in the layout file.

  9. Same as above
  10. Same as above
  11. Same as above – just delete “remote” from the name of the helper, i.e. use a standard Rails view helper, form_for
  12. Same as above
  13. Since we are not relying on Rails to do the rendering for as via a template file, we return the html chunk that we will render from Javascipt. So your create action should look like (Get it from pastie):
    def create
      @message = Message.create(:author => params[:author], :message => params[:message])
      render :partial => 'message', :object => @message
    end
    
  14. Now comes the fundamentally different part – instead of using RJS to respond to the create action, we move all our code to application.js (Get if from pastie):
    $(document).ready(function() {      
      $("#message-form").ajaxForm({success: handleNewMessage});
    
      function handleNewMessage(response, statusText) {
        $("#messages").prepend(response).effect("highlight", {}, 1500);
      }    
    });
    

    I don’t think so that this code is particularly more complicated or hard to understand that the RJS one. Everything is inside the ready() function, which means that it’s only run once the document is properly loaded. Then we declare that “#message-form” is an AJAX form, and that upon successful submission, the handleNewMessage() method should be called. And if that happens, we add the response (which is the return value of the “create” action) to the “#messages” div, just as we did in RJS. Then we apply the yellow fade! w00t!

  15. Same as above

(You can check out the code used in this post from it’s github repository).

Conclusion

As you can see, the only real difference between the obtrusive and non-obtrusive version is in the last 2 points (downloading and including the jQuery header files can be easily solved with Rails templates): instead of leaving the rendering part to Rails, we return the response as a string and dynamically insert it from jQuery. With about the same effort, we kept all the Javascript code in application.js, which is much cleaner this way (you can open up 1 file and check out all the JS/AJAX behavior in one place), especially after introducing a lot of Javascript functionality into your code – in other words, for the same amount of work we got something much better. Please try to keep this in mind when you are working with Javascript and Rails the next time – believe me, it can save you from a lot of pain!

Rails *is* (still) a Ghetto

nice_ass.png

While I know the title is both asking for trouble (because of the now anecdotal original article with a similar title) and flamebaity, please read on – my goal is not to get some great stats but rather to know your opinion about the situation and discuss the possible solutions of the problem.

How it all started…

I would not like to re-iterate what has been said on several blogs, just to summarize: Matt Aimonetti, member of the Rails Activists, gave a presentation at GoGaRuCo which contained sexually explicit images (according to some – I am not here to judge whether that’s true, and it doesn’t matter anyway, as you’ll see in the rest of the post).

I am not really discussing whether it’s appropriate to have images of nude chicks in your presentation at a Ruby conference (I think it’s not, it’s unprofessional etc. – but that would be a matter of a different post Update: Someone summed this up in the article’s reddit thread nicely: If you’re a Rails programmer, or a Ruby programmer, and you don’t decry this sort of thing, you have no business calling yourself a professional. It doesn’t matter how large your website is, how easy it was to write, how much better it is over PHP or ASP.NET or J2EE; by definition, you do not belong to a professional community. That’s all there is to it.
It’s incumbent on every Ruby programmer to either reject this sort of misogynistic sewage, or accept that you’re never going to advance the promotion of Rails in the public perception because members of the community still think it’s edgy or cool to put pictures of strippers in their public presentations.
And here’s a hint: if your decided reaction is to talk about how unimportant this is, how much it doesn’t matter, or how much it doesn’t offend you personally, you probably don’t understand professionalism at all.
) because sadly, I think there are far bigger problems here than that – shedding light on them is the real purpose of the article, not talking about pr0n at GoGaRuCo again.

Would You Walk Into a Hindu Temple with Your Shoes on?

hindu_temple.pngI have been living in India for 2 months last summer, working on a Rails startup. Maybe I am odd or something, but I knew that I had to remove my shoes when entering a Hindu temple, and _no one had to convince me (what’s more, I didn’t even think about it for a second) wether this is the right thing to do, why is it so, whether I should do otherwise etc_. This is a similar situation – I just don’t do X when speaking at a conference, if I suspect that X makes feel even one person in the room uncomfortable, whether because of his gender, race, nationality, Ruby/Rails skills, penis size or what have you – _regardless whether I think it’s fine for me, my wife, for other members of the community and/or the majority of the room_.

The trick is, how does a *hindu* feel when I enter a temple in footwear (even if that is perfectly acceptable in my country, culture, family, friends) – it’s perfectly irrelevant how do *I* feel in the given situation. Using the previous paragraph, try to apply this to a Ruby/Rails conference.

Shit happens…

Until this point in the story, I see no problem at all, and could even agree with the guys asking “what’s wrong with you, don’t make a fuss out of nothing” – the pictures Matt used are non-problematic in my book, and he had no idea they are problematic in anyone’s book – theoretically it could have worked, but the point is, *it did not*. Some members of the Ruby community got offended, and here our story begins.

…and hits the fan

One of the real problems is that after this has been pointed out, Matt still keeps answering “As mentioned many times earlier, I don’t think my presentation is inappropriate.”. As I mentioned two paragraph above, it doesn’t matter what do you think, unless of course, you don’t care about offending some members of the community. In that case you should not try to apologize at all. However, if you are trying, reciting “I don’t think my presentation is inappropriate” will not put and end to the discussion. It just doesn’t work. Why can’t you just simply apologize, admitting that this was a bad move (because it offended some, not because porn, sexual images or whatever in presentations are bad, per se) and finish the discussion?

Rails is Still a Ghetto

However, in my opinion that’s still not the worst part of the story, or to put it differently, some members of the Rails community still found a way to make things worse, by applauding to all this:


dhh_pr0n_is_great.png

OK, you say, we are all used to DHH’s style, this is just how the guy is. That’s (kind of) cool, but I heard that most of the Rails core team (and obviously Matt himself) has the same opinion – and that’s a much more serious problem, because it means that a Rails activist, backed by DHH and other Rails core members finds all this OK, despite of the fact that numerous people in the community voiced their opinion otherwise.

This is not about being a closed-minded prude, shouting for police and suing everyone using sexually explicit images in a presentation. This is not even about women, as I have seen both males and females on either side of the fence. This is about mutual respect – I don’t agree with you, but respect your feelings. Or not, as demonstrated in this case.

So Rails continues to be the most socially unacceptable framework – associated with arrogance, elitism and whatnot in the past – now add pr0n images in presentations. Thankfully RailsConf is held in Las Vegas, and that should calm down all the people who associate Rails with all this crap :-). The real problem is that people associate you with the tools you are using – think Cobol, PHP, Java… or Rails. By being part of the Rails community people associate me with Railsy stereotypes automatically, which aren’t nice at all right now.

I hear you, dear creme-de-la-creme Rails (core) member, I know you don’t give a shit, and you think this is all prude babbling – because your hourly rate is more than some of us earn in a day, and you’ll be sought after even if Rails will have a much worse image than it has now. But 99.9% of us are not in the ‘circle of trust’ and would be happier if Rails would not be constantly associated with a ghetto.

MINASWUBN

In case you are wondering what does the acronym stand for, it’s “Matz is Nice And So We Used to Be Nice”. Unfortunately, the stuff I don’t like about the Rails community is sneaking into Ruby too, it seems, as the above case demonstrates. Besides this, the count of aggressive comments and reactions on various blog posts is really disturbing to me. Please (at least Rubyists) try to avoid being contaminated by all this shit and stop thinking you are cool because you can swear on a forum (always in anonymity). You don’t have to be a douchebag just because you are a Rubyist / Rails coder, as surprising as this might sound to some.

Conclusion

I think “incidents” like this and getting more and more antisocial members are inevitable by-products of growth in a community. The questions is, whether, and if, how, do we stop them. The problem is that it seems to me the Rails “top management” doesn’t want to stop them (what’s more, even encourages them) in the first place (please prove me otherwise – maybe I don’t see the full story – I’ll be the happiest to admit that I am talking bullshit).

I have to admit I have no clue what would be the right move – burying our heads in the sand and pretending everything is fine is not. Please leave a comment if you have an idea or anything to add.

Rails Rumble Observations, part II – trends in gem/plugin usage

rails_rumble.png
In part I I wrote about the hows and whys of gathering gem/plugin usage data based on Rails Rumble submitted user information, and in this part I would like to present my findings. So without further ado, here we go:

Prototype/jQuery

I already covered this in part I, but for completeness’ sake, here is the chart again:


prototype_jquery.png

It seems that jQuery is (not so) slowly replacing Prototype as the javascript framework of Rails – which is still better (from the Prototype POV) than with Merb, where jQuery is the default framework (oh yeah, I know, Merb is everything-agnostic etc. etc. but I think vast majority of merbists are using Datamapper, jQuery etc. (?)).

Skeleton Applications

Well… this chart is rather dull:


bort.png

One in every three teams used a skeleton application (which in this context can be replaced with ‘Bort’).
The sovereignity of Bort is a bit surprising given that it’s not the only player in the field by far – there are definitely others, like ThoughtBot’s suspenders, Blank by James Golick, starter-app by Pat Maddox, appstarter by Lattice Purple just to name a few.

I am not sure about the others, but the absence of suspenders from the chart has more to do with the fact that it was not yet publicly released before Rails Rumble – I am basing this claim on the fact that a lot of people used the gems/plugins which, combined together, are basically suspenders.

However, this doesn’t alter the fact that Bort is immensely popular – great stuff, Jim.

Testing Frameworks

I think there are (at least) 2 things to note here:

  1. Testing in Ruby/Rails is not considered optional even facing a very tight deadline. Even if we assume that the 49% didn’t test at all (which surely doesn’t sound too realistic – they probably just went with Test::Unit), more than half of the teams did!
  2. Though testing tools are a much debated topic nowadays, and the winner is not clear (yet) – I would guess, based on the above results there is roughly an 1:1:1 ration between Test::Unit, rspec and shoulda *currently* – there are definitely interesting alternatives to Test::Unit.


testins.png

Mocking


mocking.png

Not much to add here – though the above chart says nothing about how much people are using e.g. Mocha with rSpec (vs. using the rSpec built-in mocking tools), one thing is clear – as a stand-alone mocking framework, Mocha reigns supreme.

Exception Notification


ex_notification.png

Another point for ThoughtBot (not the last one in this list) – Hoptoad has no disadvantage compared to the more traditional Exception Notifier (if we don’t count getting an API-key, which takes about a minute) – on the upside, you get a beautiful and user friendly web GUI.

Full-text Search


full_text.png

I found the above chart interesting for two reasons:

  1. I thought that Ferret and/or acts_as_solr are still somewhat popular – it turns out they are not
  2. I also thought Thinking Sphinx is the de-facto fulltext search plugin, and didn’t know about Xapian – well, I learned something new again.

Uploading


uploading.png

ThoughtBot did it again – Paperclip is already more popular than the old-school attachment-fu. I am always a bit cautious when someone challenges the status quo (like Nokogiri vs.
Hpricot, Authlogic vs. Restful Authentication, attachment-fu vs. Paperclip etc.) but it seems Paperclip is ripe to take over. You can find some interesting tutorials here and here.

User Authentication

Another dull graph for you:


user_auth.png

I am wondering how homogenous this chart would be if Authlogic would have appeared earlier – it seems like a strong challenger (already watched by around 260 people on github) and I am sure it will take a nice slice of the pie in the future.

What’s more interesting is the openID support: more than one third of the apps offered openID authentication, and quite a few of them *solely* openID.

Misc

  • factory_girl was used to replace traditional fixtures in every 6th of the apps!
  • HAML/SASS is quite popular – used in about 20% of the applications
  • Hpricot was the only HTML/XML parser used (in 7 apps alltogerher)

What I am happy about the most is that there is still a lot of innovation going on in the Rails world – as you can see, newer and newer plugins/gems are appearing and in some (in fact, a lot of) cases are dethroning their good ol’ competitors. There is a lot of competition going on in almost every major area of Rails web development, and this is always a good thing.

Rails Rumble Observations, part I – jQuery on the Heels of Prototype

rails_rumble.png
As a Rails Rumble judge, I spent quite some time reviewing the applications and I noticed several patterns regarding the gems/plugins used during the 48-hour contest. The participants were asked to submit whatever tools they were using to build their app. With a few exceptions they complied, creating an interesting data set to observe the current trends in the Rails world.

Collecting the Data

Unfortunately it was not possible to gather the information automatically using screen scraping or other mechanical methods, since the input was varying from free text (stating details like ‘we used Rails, macs, TextMate, cocaine (the drink!)’) etc. to the output of _gem list_ – and everything in-between, not following any guideline (perhaps because none was given). So I hacked up a small app with a single form and harvested the info manually. I only collected data for the first 100 entries, for two reasons: the stuff used in the rest of the apps was pretty much the same, and mainly: the task was rather daunting 🙂

Why Does this Matter?

I believe that because of the rules (I mostly mean the 48-hour deadline) the findings are quite representative – I am sure that every team reached after the most productive/easy to use/effective tool they could grab since the deadline was tight. Rails Rumble is not about experimentation or showing off some new shiny toys, but lightning fast hacking aided by state-of-the-art gems and plugins so I think it’s safe to assume that the tools used here are pretty much the crème de la crème of the Ruby/Rails world.

Prototype vs. jQuery

In the first exhibit, I’d like to check out Prototype vs. jQuery usage. To prepare this chart, I took the extra mile and didn’t rely on the user-supplied data, but opened the pages by hand and checked the headers for Prototype/jQuery javascript includes. Here is what I have found:


prototype_jquery.png

1 team was using mootools, the rest of the cake is divided between Prototype and jQuery.
Most probably the real result is even more in favor of jQuery, I would guess well above 60% – all the teams that added jQuery to their application.html.erb were actually using it (why would they bother adding it otherwise), while this is not necessarily true for Prototype, which is included by default and maybe some teams didn’t even use it, just didn’t care to delete it (as you will learn in the next part, every 3rd team used bort, which includes the Prototype/script.aculo.us files by default).

This is not the first indicator of jQuery’s rising popularity in the Rails world – Hampton Catlin’s Ruby Survey found out the same (i.e. jQuery is more popular right now than Prototype). Merb is using jQuery by default.

Is Prototype Dead?

My favorite Austrian Ruby-hacker friend told me over lunch a few weeks ago: ‘Prototype is dead!’. I think this statement is questionable at the moment to say the least, since Prototype is still the default javascript framework of Rails and this is not likely to change anytime soon due to the fact that Prototype is heavily used by 37singnals (and probably entrenched into other older Rails-apps as well).
However, the trend seems to be that jQuery is spreading really fast, replacing Prototype in a lot of cases.

So be sure to check jQuery out (it’s dead easy to install and use it) – I immediately fell in love with it (maybe I was used to Hpricot-style CSS selectors too much?) and I am happily using it in my projects now.

The Next Episode

Which testing tools are used by the community? How about rails skeleton apps? OpenID support? exception-notifier or hoptoad? attachment_fu or paperclip? mocha or flexmock? factory-girl or traditional fixtures? Find out in the next installment!

Random Links from the Web, 21-04-2008

Live Validation – Easy Client-side Javascript Validation

live_validation.pngUpdate: Sergio, the author of the livevalidation rails plugin updated the plugin so you can disregard the finale of the article (validates_confirmation_of is working, as well as the newest version of livevalidation, 1.3 is used in the plugin – so no additional tweaking is needed, install and validate away ;-))

Surely I am not the only one who was a ‘bit nervous’ (that was a mild euphemism) when his carefully entered data disappeared after submitting a form to the server. Nowadays web applications are doing better than that – valid data is saved and only the problematic fields are pointed out.

Of course even that feels so 1990’s now. A contemporary (ehm… web 2.0?) web application is expected to validate the form on the client side already (WARNING! That doesn’t mean at all you shouldn’t validate on the server side though – client side validation is for the good guys but you should still look out for the script kiddies et al), pointing out the errors on the fly so there is no need to come back and change/edit those fields after submitting a form.

My library of choice is livevalidation, which has a Rails companion too – if you are using Rails form helpers and standard validation on your models, you don’t have to touch anything just install livevalidation (=drop it to your javascripts folder, it’s a single .js file). w00t!

The only major shortcoming (from my POV) of the Rails plugin is that validates_confirmation_of is not implemented. However, it’s easy to add it via standard javascript:

<input id="user_password" name="user[password]" size="30" type="password" />
<input id="user_password_confirmation" name="user[password_confirmation]" size="30"> 
<script type="text/javascript">
var validate = new LiveValidation('user_password_confirmation');
validate.add( Validate.Confirmation, { match: 'user_password' } );
</script>

That’s it!

One more note: the Rails plugin contains version 1.2 but there is a newer version, 1.3 so be sure to replace it.

The Top 10 Ruby/Rails Blogs

ubuntu
In my quest to whip my feed reader’s Ruby/Rails related content into shape a bit, I made a little research to find out which Ruby/Rails blogs are the most popular at the moment. I had given up on following most of the blogs systematically a long time ago – it is becoming increasingly hard to keep track of even the aggregators, not to talk about the blogs themselves. There are hundreds of Ruby/Rails blogs out there right now (I am talking about the ones found on the few most popular aggregators – in reality there must be much more of them), so it is clear that you need to pick carefully – unless you happen to be a well-paid, full time Ruby/Rails blog reader (in which case you still would have to crank a lot to do your work properly).

OK, enough nonsense for today – let’s see the results counting down from the 10th place! If you are interested in the method they were created with, or a longer, top 30 list from technorati and alexa, check out this blog entry.

10. http://weblog.jamisbuck.org/ by Jamis Buck.

jamisbuck

Jamis Buck “is a software developer who has the good fortune to be both employed by 37signals and counted among those who maintain the Ruby on Rails web framework”. He is mostly blogging about (surprise, surprise!) Rails – of course on a very high level, which could be expected from a Rails core developer. Very insightful posts on ActiveRecord, Capistrano and other essential Rails topics delivered in a professional way.

9. http://weblog.rubyonrails.org by the Rails core team

weblog_rubyonrails

This is the “default” Ruby on Rails blog, used for announcements, sightings, manuals and whatever else the RoR team finds interesting :-).

8. http://www.slash7.com by Amy Hoy.

slash7

This is a really cool little site – Amy is a very gifted writer and designer, publishing very insightful articles as well as the nicest (hands down!) cheat sheets about different Web2.0, Ajax, Rails and that sort of stuff. Definitely worth checking out!

7. http://errtheblog.com by PJ Hyett and Chris Wanstrath.

err_the_blog

A very serious blog of two Rails-geeks about advanced topics (but very well explained – so if you are not totally green (#00FF00) you should do fine). Among other things, they have contributed Sexy Migrations to Rails recently.

6. http://nubyonrails.com/ by Geoffrey Grosenbach

nubyonrails

Geoffrey is the author of more than twenty of Rails plugins, (including gruff, my favorite graph drawing gem), a horde of professional-quality articles and the PeepCode screencast site. Do I need to say more?!

5. http://redhanded.hobix.com/ by _why the lucky stiff.

redhanded

_why is probably the most interesting guy in the Ruby community. He is the author of (among tons of other things) Why’s Poignant Guide to Ruby, HPricot, the coolest Ruby HTML parser, Try Ruby! (a must see!) and Hackety Hack, for aspiring wannabe programmers who want to hack like in the movies! The list goes on and on… This guy never stops. If someone will ever invent the perpetuum mobile, he will be it (in Ruby, of course).

4.http://hivelogic.com/ by Dan Benjamin.

hivelogic

Dan’s recent work include Cork’d, a web2.0 wine community site or the A List Apart publishing system. He does great podcasts with various guys.

3. http://mephistoblog.com/ by Rick Olson and Justin Palmer

mephisto

Personally I was quite surprised that a blog concentrating on such a narrow topic (in this case the mephisto blogging system) could grab the 3rd place – so I have checked both alexa and technorati by hand just to be sure, and it seems that everything is OK – mephistoblog is ranked very high on both of them, justifying this position. After all, mephisto is the leading blog system of Rails!

2. http://www.rubyinside.com/ by Peter Cooper.

rubyinside

This blog is my absolute favorite from this top 10 list (actually, from all the Ruby blogs I have encountered so far). I am definitely with Amy Hoy, who said If you had to subscribe to just one Ruby blog, it should be this one. If you would like to know what’s happening in the Ruby/Rails community, rubyinside is the place to check. If there is no new post here, it’s because most probably nothing happened!

And the winner is: http://www.loudthinking.com/ by David Heinemeier Hansson.

loudthinking

Well, what should I add? David is the author of Ruby on Rails, so no wonder his blog topped the list!


Conclusion
It’s interesting to note that nearly all the blogs listed here are mostly pure Rails ones – rubyinside (mixed Ruby/Rails) and redhanded (pure Ruby) being the two exceptions. It would be interesting to generate such a list for Ruby blogs – though I am not sure how. The sources I have used (most notably rubycorner) aggregate both Ruby and Rails blogs) – so it seems there are much more Rails bloggers out there (or they are much better (with the exception of _why) than the Ruby bloggers).

I would really like to hear your opinion on this little experiment – whether you think it makes sense or it is completely off, how could it be improved in the future, what features could be added etc. If I’ll receive some positive feedback, I think I will work on the algorithm a bit more, and run it once in say every 3 months to see what’s happening around the Ruby/Rails blogosphere. Let me know what do you think!

If one is thinking about creating a site for affiliate marketing to earn some extra cash they should thoroughly research a few things. To start with look for a cheap company that sell domains for your domain name registration. Next get a cheap, yet reliable web hosting company to host your site on. These can be easily distinguished as they hire many cisco certified professionals. The generally carry 642-371 certifications. Then look into online backup for your files to avoid data loss. More over perform directory submission to get indexed in the search engines. Getting a+ certificate yourself is not a bad idea since it will help you get through the process with much ease.

Great Ruby on Rails REST resources

REST-cheatsheet
If I had to choose the single most not-really-well-understood, mystified, unsuccessfully demystified, explained and still not-really-grasped topic in the Rails world (and beyond), my vote would definitely go to REST. It seems to me that there are two types of people in the world: those who don’t get REST (and they think it’s a basic postulate to rocket science explained through quantum theory) and those who get it, and don’t understand the former group (unless they are coming from there, that is).
I have been playing around with RESTful Rails recently. Below is my collection or Rails REST howtos, tutorials and other resources I have found so far and which were adequate for my transition from the first group to the second :-).

You should definitely begin with REST 101 – then check out the other stuff as well!

Please leave a comment if you know some more (just for completeness’ sake – I think the above resources should be enough to grasp RESTful Rails both theoretically and practically.

Creating a site and uploading is considered to be the easy part these days. Especially with languages like ruby on rails you can develop sites in no time. Companies providing hosting services give you a wide variety of options to choose from for your hosting services such as asp hosting or php hosting. Not only that but they also hire 350-040 certified to provide you quality services. Then yahoo hosting provides simple methods for uploading site. With the use of computer backup software you can easily avoid data loss. The actual time consuming part is working on the site’s search engine ranking. Not only does it take time but it is also expensive.

Getting Beast up and Running on Dreamhost (for the Truly Lazy)

Though dreamhost offers phpBB as one of their one-click install goodies (ergo it is the easiest to install of all forums since you almost don’t have to do anything), I have been looking for something different. To me, phpBB’s interface was always quite unintuitive and too heavy – I wanted something smaller, easier, more compact. The problem was I did not know what should I search for – until I came across beast, a lightweight forum written in Ruby on Rails. It was love at the first sight!

When it comes to tools I am using, I am really language agnostic – this very blog uses WordPress (PHP), I am using Trac (Python) to track my projects, mediaWiki (PHP) is my preferred wiki etc – so even if it may seem so, I did not choose beast because it is written in Rails (although +1 for that :-)), but because of the design and ease of use. My first thought after trying it was ‘wow, this is as easy to use as a 37signals app’ – it’s really that intuitive and well designed!

Well, this sounds fine and all, but installation on dreamhost was a different story. Thanks God I have found a superb, step by step HOWTO here. However, even after following all the steps, I got ‘incomplete headers’ and other problems, which I have managed to fix – here are some additional comments to the HOWTO:

6. You can forget about this point; as the HOWTO says, it is already installed on DH and it will work without any problems.
7. Forget about ‘development’ and ‘test’, however be sure to get ‘production’ right, as the next step will not work otherwise. It should look something like this:

production:
  adapter: mysql
  database: beast_prod
  host: mysql.myhost.com
  username: us3r
  password: p4ss
  port: 3306

8. For me it worked only *with* the RAILS_ENV=production parameter specified.
9. You can change the salt to anything – it just must not stay the same. The easiest thing is to add or remove a random character from the string.
12. The shebang should be updated to #!/usr/bin/ruby
13. The || should be removed, i.e. it should read:

ENV[‘RAILS_ENV’] = ‘production’

14. Make sure you change the permission of those directories only – I have changed everything recursively, destroying the executable flag of dispatch.fcgi :-).

Now you should apply the ‘GetText patch’ – it can be found later in the thread. After you should be up and running!

After playing around, I have found that the user listing is not working – fortunately I have found this as well in the forum. The solution is:
app/views/users/index.rhtml line 3 should be modified to

%lt;% form_tag '', :method => 'get' do -%>

Enjoy this great forum!

The Sadly Neglected Pickaxe-killer

I have just finished reading Ruby for Rails: Ruby techniques for rails developers from David A. Black. Here is my (WARNING: highly opiniated) review…

I have been a Python fanatic for quite some time, and decided to give Ruby a shot. After some googling, I found most references pointing to a book called the ‘Pickaxe’. Quite a strange name for a programming book, thought to myself, but picked it up nevertheless. I have been instantly converted after a few dozen pages – mining Ruby with the pickaxe was an awesome experience! Since then, I have finished reading the second edition and became a Ruby enthusiast.

After lurking around a bit, I have learned that the common standpoint is that every newcomer/beginner should grab a copy of the Pickaxe to get started. Based on my previous, positive experience I could not agree more – until I came across R4R.

Ruby for Rails is awesome: The technical depth is just right to not distract beginners, yet detailed enough for even the more advanced readers. I did not skip a single page (though years of programming experience and tons of similar programming books I came across during that time could allow me) and finished reading it in no time.

I could write some more about how cool this book is (and it would deserve every bit of it), but I think you can read about that just anywhere (a nice review can be found here), so I would like to point out something different: If we consider the Pickaxe THE book for newcomers, then IMHO R4R is a Pickaxe killer.

Don’t get me wrong: I am a great fan of the Pickaxe, which is another very high-quality technical book – but if someone wants to apply the ‘right tools for the right job’ principle, I think newcomers who already decided to learn Ruby should grab Ruby for Rails. Programming Ruby’s Part I is absolutely well suited to get the ‘feeling’ of Ruby, and it’s next chapters are great to learn the advanced stuff – however in my opinion, the leap between the first and the next chapters is too big for an absolute beginner. Ruby for Rails is there to fill this gap.

Maybe someone might not advice this book to a newbie eager to learn Ruby, since it has ‘Rails’ in it’s title. However, R4R is still primarily a Ruby book, and while I found the Rails parts to be very helpful, I can recommend it to anyone who would not like to learn Rails at all – though the full potential of the book comes through if one would like to learn both.

Conclusion: Ruby for Rails is an awesome book on Ruby. If you are beginner, would like to get a solid understanding of the Ruby principles, or your goal is to polish up your Ruby knowledge to grasp the Rails framework – R4R was made just for you! Check it out – you won’t be disappointed.

Announcing screen-scraping series

I am planning to write a series of entries on screen scraping, automated
Web navigation, deep Web mining, wrapper generation, screen scraping from
Rails with Ajax and possibly more, depending on my time and your feedback.
Since these entries are going to be longer, I will be posting them to
separate pages, and announce them on my blog.

The first article is ready, you can read it here.

It is an introduction to screen scraping/Web extraction with Ruby,
evaluation of the tools along with installation instructions and examples.

Feedback would be appreciated (leave your comment here/on the article page, or
send me a mail at peter@[name of this site].com), I will update/extend the
document and publish new ones based on your feedback.

Programming is hard

Programming is great fun (mainly with Ruby ;-). However, this statement does not contradict with the fact that sometimes programming can be also hard. I came across a nice site today which can offer some help in these moments: Programming is hard. Judging from the size of Ruby/Rails/ActiveRecord tags (there is even a script.aculo.us tag!) it seems that it has a nice dose of Ruby/Rails stuff – solutions for common problems and also links to tutorials, frequenty asked nuby questions etc. Be sure to check it out!

Ruby on Rails Migrations Reloaded

In my previous post on migrations i wrote that “…they are not covered in any of the basic books on RoR”. Well, this statement does not hold anymore, since Agile Web Development with Rails, 2nd ed. is already creating the models with migrations.

While the last part of the post (why are migrations so cool) is still up-to-date, they way of creating migrations is different from 1.1 on, so i have decided to review the topic and add some new points, too.

Migrations are now created automatically with the model

In my previous post, i have been creating the migration manually with the command

ruby script/generate migration ProductMigration

However, as of Rails 1.1, you don’t have to do this anymore. When you generate the model (let’s stick with the Product model as an example) the migration is automatically generated:

ruby script/generate model Product
...
... #some lines omited
...
create db/migrate/001_create_products.rb

Now you can edit the file db/migrate/001_create_products.rb to contain something like this:

class ProductMigration < ActiveRecord::Migration
def self.up
create_table :products do |table|
table.column :title,       :string
table.column :description, :text
table.column :image_url,   :string end
(rest of the file omited)

Then run

rake db:migrate

To update the database. That's even easier than in the previous versions of rails!

Valid column data types and possible options

Valid columns are:

integer, float, datetime, date, timestamp, time, text, string, binary and boolean.

Valid column options:

  • limit ( :limit => “50” )
  • default (:default => “blah” )
  • null (:null => false implies NOT NULL)

string is the equivalent of varchar(255), so if you would like to have a string column (called title) of length 100 instead of 255, with default value 'Some title' and to forbid NULL value, you have to type

table.column :title,
:string,
:limit   => 100,
:default => "Some title",
:null    => false

Generating test data

I am quite sure you know the situation when you want to test something quickly and you waste precious time to generate some test data, which you trash after the testing just to find yourself in the same situation later?

Well, migrations can help you to prevent headaches because of this, too. Here is how:

ruby script/generate migration create_test_data
Create db/migrate/002_create_test_data.rb

You can create test data inside the migration file like this:

class ProductMigration < ActiveRecord::Migration
def self.up
Product.create(:title => 'My cool book about the meaning of life',
:description => '42',
:image_url => /images/cool_book42.png)

You can now commit this migration to the RCS you are using, and modify/add more test data later.

The other advantage is that your colleagues won't spend time writing dummy test data either: they can just check out this migration and happily use the provided tests.

If this is still not enough for you...

You can write SQL statements inside the migrations. For example:

execute "alter table items
add constraint fk_items_products
foreign key (product_id) references products(id)"

However, use this with care since you have to write native DDL statements, which violates one of the fundamental 'cool factors' of migrations: independence from DB vendors.

Conclusion

The Agile Web Development with Rails, 2nd ed can be considered as the Rails bible and since it is promoting migrations as the definitive way to handle your DB issues, i think migrations will become (in fact the already did for lots of people) the state of the art. After using them for a while and enjoying the power and flexibility they provide without having significant drawbacks, i don't really see why should one not use them in the future.

db:session:create problem (?) in the depot app

As I wrote in my previous post, I am currently reading/coding the depot example from the Agile Web Development with Rails book. I had one unclear issue so far – maybe someone can help me to find it out: I did something wrong or this is really a typo in the book?

Putting sessions in the database
According to the book, this should be done with

rake db:session:create

However, after entering this command to the console I got:

(in /home/peter/development/src/railsprojects/depot)
rake aborted!
Don't know how to build task 'db:session:create'

After some playing with rake –help, I have found the –tasks switch:

rake --tasks

and here I have finally found the remedy for my problem: the correct command is

rake db:sessions:create

(note the additional ‘s’ character)
Is this because my rake version is too old/too new or this is a typo in the book?

After this modification everything worked again as intended.