Ruby On Rails


I was sitting at the Lone Star Ruby Conference and during one of the workshops the speaker mentioned we could find a pair programming partner for the next segment of the workshop. Being a little shy and the only person I knew there was with his co-worker, I thought it would sure be nice to easily find a pair programming partner! During the break I had this idea and bought rubypair.com … I had hoped that during the conference I would find someone that also would share my vision and keep me on task to finish it. I had heard Evan Light during his talk when he mentioned has has open “office hours” where you can make an appointment to pair with him. So I found him and told him of my idea. He liked it and we agreed to pair on rubypair on the last day of the conference. We were trying to get it done so we could demo at the lightning talks but we kept wanting to try new and shinies (rails 3.1, sass, compass, mongodb etc) that we didn’t make it in time! But we made some progress and said we’d pair remotely to work on it.

The next weekend we set up time to pair on it and we worked through somethings. I was pretty rubied out though having spent the weekend prior to Lone Star Ruby Conference at an all night-hack fest in Austin. Evan took the bull by the horns (yes I live in texas now!) and worked out more kinks, David Browning did the logo and site design and Evan implemented it with SASS and Compass. Others helped out almost immediately and we had pull requests! We deployed RubyPair.com on Sept 3! See the Contributors list for the growing list of contributors.

Give it look and never code alone!

Repo: https://github.com/rubypair/rubypair
Tasks: https://github.com/rubypair/rubypair/issues

Recently I worked on a project where I needed certain config variables for staging, production, test etc and I wanted to store all these in a yaml file. I could set them in the different environments files but I prefer them all in one file.

Create a file in the config/initializers .. I called it 00_load_app_config.rb so I can be sure it gets loaded first. In it I have only a single line

RUBY:
  1. APP_CONFIG = YAML.load_file("#{Rails.root}/config/app_config.yml")[Rails.env]

Then I create a yaml config file at config/app_config.yml

RUBY:
  1. base: &common
  2.     company_name: 'The Awesomest Company Evar!'
  3.     api_username: 'api_user'
  4.     api_password: 'bob123'
  5.  
  6. development:
  7.     <<: *common
  8.     api_hostname: 'http://api-development.myawesomesite.com'
  9.     twitter_app_key: 'fff'
  10.     twitter_app_secret: 'fff'
  11.  
  12. staging:
  13.     <<: *common
  14.     api_hostname: 'http://staging-api.myawesomesite.com'
  15.     twitter_app_key: 'sss'
  16.     twitter_app_secret: 'sss'
  17.  
  18. test:
  19.     <<: *common
  20.     api_hostname:  'http://test-api.myawesomesite.com'
  21.     twitter_app_key: 'eee'
  22.     twitter_app_secret: 'eee'
  23.  
  24. production:
  25.     <<: *common
  26.     api_username: 'api_user_prod'
  27.     api_password: 'bobprod123'
  28.     api_hostname: 'http://production-api.myawesomesite.com'
  29.     twitter_app_key: 'yyy'
  30.     twitter_app_secret: 'yyy'

The variables in the common section are applied to every environment and overridden like in the case of production, which overrides the api_username and api_password. In each environment they pull the company_name from the common block.

To use a value in your rails app, use the APP_CONFIG array, like
APP_CONFIG['website_name'] or APP_CONFIG['twitter_app_key'] and it will always return the value for the environment currently in Rails.env

Thanks to my friend Rath who showed me this, I changed the name from config to app_config because I liked it to be more specific, but use whatever name you like!

I recently went on a small vacation and finally had some time to catch up on some railscasts! I like to setup a project and "play along" with Ryan Bates and pause/play and work through the examples. With all my experimentation/playing I keep a git repo at http://github.com/rubygeek/rubygeek where I keep code for reference later. Sometimes when trying to remember if i did something, I grep a keyword or two on the root directory and see if I have done something with it before. I can put notes in the readme file for each project, so I can remember what resources I used.

#264 Guard - Setups up monitoring for files to run something like tests, compile coffee script or sass. The cast shows how to use it to run your rspec tests. It shows liverefresh, with that and a plugin it will automatically refresh your browser!

#262 Ancestory - I spent a good deal of time using acts_as_commentable_with_threading and although its pretty good, I think now I will change to using this, it seems like it will be more efficent on queries and has more scopes defined.

#254 Kaminari - Wow, this is totally awesome! I did have to do some digging to figure out will_paginate for rails3, and this is way better as it is a rails engine, so its soooper easer to customize. The labels for the next/previous are stored in the language file (ie. en.yml) so if you support multiple languages, this is awesome. If you need to customize beyond css, you can run the rake command to generate the views.

#271 Resque - I might need to do something like this soon for a project, so I was happy to see this. It was pretty easy to do and I like the admin interface to see what is going on. Even more cool, is it is written in sinatra and you can hang it of your rails app if you want and assign a route to it. Definitely a fun screencast to follow along with!

#269 Template Inheritance - Finally, this makes perfect sense. Available in Rails 3.1 you can have an Application directory in the views directory and there you can place things common to all views, like header, footer, sidebar etc ... then if you need it customized footer for say the Products page, you can put a footer partial there and that is used on product pages. Previously you had to make a directory like common, shared. etc etc and it always seemed hackish to me.

Recently Ryan has put before and after version of the code in his gitrepo, and though I usually try to do it all myself, I did grab his before code for the Template Inheritance.

Thats about all for now, give those a try and practice ruby!

I never really used a debugger until I did Java. Before that I did what was called "PHP Debugging" which is littering your code with print statements until you figure out what you need to know, then going back and making sure you deleted them! I sometimes would put a unique string like

print "QWE" . $myawesomevar

Or something like that, then going back and searching your code for QWE (just picked something that was easy to type!). But all that gets rather annoying. They might have nice debuggers for PHP now, I haven't really done php in 4-5 years. I really didn't understand the power of breakpoints until I did java and I thought that was pretty cool. Now that I do all ruby, I sort of miss eclipse (I didn't actually think I'd ever say that...) since all I use right now is textmate and vi which don't have the built debugger support that eclipse does. Some of the newer ruby editors might, I haven't spent any research on them.

I found ruby-debug and it works great! You can set a breakpoint and then climb inside your application and peek around and see what is going on. I've done this in controllers and even in test mode.

If you use passenger, you can still use it but its a little tricky to setup. This blog post from duckpunching.com has some neat tips and a rake task to make it easier. Be sure to start the rdebug -c from the console after you have set a breakpoint and reloaded your page.

If you are using passenger, you can't use the irb command inside of the ruby-debug console, but I found that most of the time just being able to poke around the variable space inside my app has been enough for me to understand what is going on.

There are quite a few commands available in the debug console, but these are the ones I've used:

help - view the list of commands
l list - this shows context around the current line the debugger is on
n next - moves to the next line
p print - print a variable
irb jump to console - I dont use this very often and it doesn't work if you are using passenger
c cont - continue to end of breakpoint or end of page load, after I have seen what I want to see I do this to get out of the console

Resources

Anyways, hope some of you find it useful and happy debugging :)

Update: I wrote this in preparation for a short talk at AustinOnRails while giving the talk, the group had some suggestions:

put in a ~/.rdebugrc

set autoeval
set autolist

autolist - will run list command when you enter
autoeval - will eval each line, so instead of "eval @profile" to get it to print, it will automatically eval

doing m [object] can show methods in a nice table format. Thats cool, i have often gone to irb and did String.methods.sort but that is kinda hard to read.

Anyways, good stuff!

Trying something new .. HAML... I saw it a couple years ago, I was like "ehh.. umm.. nah" ... But working on the DevChix site, it seems like it will be our choice instead of erb for templates so I thought I'd give it a try.

So here's some straight up html + erb

RUBY:
  1. <h1>Listing users</h1>
  2.  
  3. <table>
  4.   <tr>
  5.     <th>Username</th>
  6.     <th>Email</th>
  7.   </tr>
  8.  
  9. <% @users.each do |user| %>
  10.   <tr>
  11.     <td><%=h user.username %></td>
  12.    <td><%=h user.email %></td>
  13.     <td><%= link_to 'Show', user %></td>
  14.     <td><%= link_to 'Edit', edit_user_path(user) %></td>
  15.     <td><%= link_to 'Destroy', user, :confirm => 'Are you sure?', :method => :delete %></td>
  16.   </tr>
  17. <% end %>
  18. </table>
  19.  
  20. <%= link_to 'New user', new_user_path %>

And same with haml:

RUBY:
  1. %h1 Listing users
  2.  
  3. %table
  4.   %tr
  5.     %th Username
  6.     %th Email
  7.  
  8. - @users.each do |user|
  9.   %tr
  10.     %td
  11.       = user.username
  12.     %td
  13.       = user.email
  14.     %td
  15.       = link_to 'Show', user
  16.     %td
  17.       = link_to 'Edit', edit_user_path(user)
  18.     %td
  19.       = link_to 'Destroy', user, :confirm => 'Are you sure?', :method => :delete
  20.  
  21. = link_to 'New user', new_user_path

I am not totally sold, but.. it is an interesting kind of markup!

Let me know if you see a better way to write it or if you prefer another markup language!

Even though I don't do ruby at work, I do it for fun on weekends. I paid for my own self to go to the WindyCityRails conference and tutorial on Cucumber, RSpec Testing. It was well worth the money!! Not many things can get me to go up to Chicago early in the morning and on a weekend!

I went to a 3 hour tutorial class "Behaviour Driven Rails with RSpec and Cucumber" ... in my limited time I can spent with I've had a hard time getting my head around cucumber. I did rspec alot a few years ago, so thats a piece of cake. David Chelimsky and Corey Haines. 4 days before the conference, they sent an email to attendees of the tutorial with a list of resources to read and libraries to install. I worked all week on watching railscasts.com videos on cucumber, factories, testing. I always like to try things out myself first, then I am familiar with it when I go "to class" :) Dave and Corey did the class pair programming style..which was totally fascinating. There was one laptop, two wireless mice and one wireless keyboard. Dave typed on the laptop keyboard and Corey typed on the external keyboard. One would talk and explain things while the other typed. They took turns. It was really awesome. After watching them program, then they told us to split up in pairs and do the same thing for another scenario. I was sitting between two people so I kinda bounced between them. The one on my left didn't have the same version of rails, so he typed on my keyboard and we took turns. It was awesome, I had not really done pair programming quite like that before. They bounced between cucumber tests and rspec tests. I wish I could have recorded video and played it back in slow motion!

The regular talks:

Better Ruby through Functional Programming
Dean Wampler, Object Mentor, Inc.

I started to learn haskell once.. bought the O'Reilly book (which is excellent with little exercises)... but thats as far as I got with functional programming. This talk was interesting with code samples of ruby. We were challenged to learn a functional programming language. He mentioned others like scala, erlang ... hmm what to choose!

Super-easy PDF Generation with Prawn and Prawnto
John McCaffrey, Pathfinder Development

I have not had to make PDFs with ruby yet...but now I know there are some great libraries. Cool part of this is John was making a PDF of a ruby app, pulling in twitters happening at the conference and using Googles graphs APIs to make pretty graphs! I saw alot of people saying "I didn't know that Google had graph APIs!!!" :)

“Comics” Is Hard: On Domains and Databases
Ben Scofield, Viget Labs

When the talk started Ben asked for a show of hands of who reads comics? I meekly raised my hand. My husband is a comic book fan and I read them on occasion. I sat at his table for lunch and he asked me about it. I was surprised he saw my hand, iwas sitting near the back! This talk didn't have much code, but talked about the number of attributes that comic books have (title, issue, theme, publisher, etc) and how hard it was to model in a relational database. He talked about couch db, mongo ... i haven't tried any of those, but I might now that I know it can be the best choice for some data sets.

Rails 3 Update
Yehuda Katz, Engine Yard

Yehuda talked about whats coming up in Rails3. But by this time I was kinda brain dead and was trying to make plans for dinner!

Devchix!!!
A few of the local chix came to the after party and hung out. There was a few at the conference I had not met yet and a few I invited to join! It was awesome. It was so fun. I caught up some of my ruby buddies I hadn't seen in awhile and made some new friends. I was sad to see it end...

I know that mentioning Rails and PHP in the same sentence is taboo and can incite many flame wars. But hear me out -- Some say one of the "downfalls" of PHP is that its so easy to write applications and just about anybody can write a PHP if they put their mind to it and learn the syntax. As a result, PHP Applications have a long history of badly written, insecure code and has really been shunned by many advanced developers (aside from many poorly named methods, I think PHP is alright!).

In recent months I've been recruiting for a Rails Developer at my company, in Chicago. I did a phone interview and the guy couldn't name me any rails sites he reads, or name the 7 rest actions, or even tell me what version(s) he uses. Now, I'm not claiming to be an expert, but I would think that even an average Rails developer would know that.

I've also seen code where the developer doesn't quite get MVC. You don't need to be validating values in your controller and adding error messages to @model.errors.add for example. You don't need to be setting up display labels in your model. You don't need to be counting things in a helper method. I was thinking, why is it so hard? Is it because in mostlanguages we have had free reign to interpret MVC however we pleased? I know I spent many years in PHP trying to develop a DAO. I made an object that returned a row of data, with methods to access the fields. But what about a collection? what is that? I experimented with an array of objects but I felt that was too wasteful. Iexperimented with a DaoSet that was made to hold a collection -- complete with iterators! I even struggled with MVC and knowing what went where...when I saw Rails it was like someone who met their true love -- this is it!

After experiencing Rails, I realized hey I can do some of this in PHP! I wrote a simple MVC framework in PHP. I called it StupidlyEasyMVC Framework. I was able to use it at work (at the time, I was still at a PHP job. Some say I talk about that time in my life as if it were a prison sentence haha). SO I was able to apply things I learned from Rails, into an existing structure at work. Just like the guy from CDBaby -- I couldn't drop my existing PHP site and just start converting to Rails, but by starting to gradually switch from what I had to an MVC structure, it made my code cleaner and easier to work with.

So as I look for advanced rails developers, I find they are far and few between. Either they are hotshot consultants or working on their own startup. What makes a rails programmer "get it" and really work with the framework instead of against it - still trying to write as they always have?

Here are some things you can do if you feel you are still writing PHP or .NET code in rails..

Get a project. You can read and dabble all you want, but if you don't have a project, you won't be forced to learn. Along with that, you need a timeline to force you to keep at it!

Watch all the Peepcodes! especially the REST and rspec episodes. I've search hard and long enough for answers, to find comprehensive training in ONE spot, in such an easy to learn format is awesome. I constantly talk about peepcode and I won't work with anyone who hasn't watch them.

Peepcode Code Review - their first book, full of helpful hints and gotchas that will really help you move beyond a beginning developer

Ruby Inside Blog - www.rubyinside.com

Jay Fields - http://blog.jayfields.com/

Obie Fernandez - obiefernandez.com

Books:
Agile Web Development with Rails - If you are doing Rails and don't have this book, get it! It is the bible of rails! I don't care if you have the first edition already, this will save you time!
The Ruby Way by Hal Fulton - because if you don't know ruby, you will never be a good rails developer.
The Rails Way by Obie Fernandez - its good because I tech edited it before publication! It is a comprehensive instructional and reference book -- all in one. I cannot wait to get my hands on a paper copy of this to keep at home and one for work. (just got one this week...I'm ecstatic)

Well this has been mostly a rant but hopefully a help resource to move into more advanced development of rails. If you have other insights into this problem or suggestions for how to improve, please leave a comment!

Its been a while since my last post! Been so busy working on ruby, at work, at home and play. Some of the interesting things I've been doing recently:

Conductors - I've been fascinated by the Presenter Design Pattern posted by Jay Fields and more here and read up everything I could, still it wasn't quite what I wanted. Then I found the blog entry by New Bamboo Conductors and Presenters. Basically a conductor goes between model and controller whereas a presenter goes between a view and model. A conductor is what I've been wanting -- a way to group to associated models such as customer and an order and work with it as one. I can call save on it,I can pass it to a form builder (which is sort of present-y but I don't care) Anyways, I am working on a blog post about it.

Exporting data to fixtures - for one project, I wanted to extract a subset of data to fixtures so I can load into a staging site for testing. Say I wanted to take the most recent 100 orders, which also grabs the associated record from customers, addresses, invoices, customer categories and products table. With the help of one of the recipes in the Rails Recipes (Pragmatic Programmers) I was able to write a rake task to export the data. The example exported all data from every table except schema_info. I rewrote it with explicitly naming the tables and the queries needed. I'll write up something on this too, including how I got around my yaml array being TOO large(I think thats the prob anyways) to import! doh!

Admin interface - I used the restful_authentication plugin. That's great for a sign up and login page but I also wanted a way to administer users. I debated on whether to make an controllers/admin/users_controller and banish anyone trying to access that controller and not an admin ... or, I can add the CRUD methods to the controllers/users_controller and check for admin at the start of the CRUD actions that only admin can use. I turned to the wisdom of the DevChix mailing list (sorry boys) and got some good ideas from the Chix. I need to write this up as well!

Facebook App - Not Rails, but could be. I was recently contacted by someone to make a facebook app. I've never made one, so that night I set out with PHP to write a little app. Within a few hours, I had a simple app. I let the company know that I figured out how to do it, and what was the next steps in getting the contract? *poof* they never emailed me back. I think they figured -- well if SHE can do it two hours, we can probably figure it out ourselves! haha... but it was fun anyways.

Rspec and Mocks - It took me awhile to get the hang of mocks... but determined I figured it out. Nice. :) Right now I am just using the mocks in rspec, but want to look at other mocking frameworks to see what the difference is.

Autotest and snarl/growl - I now use autotest all the time on all my projects. I saw on PeepCode that Geoffery used growl to make a small window pop up on his mac with the status of the last run test. I showed my husband and said SEE? I need a mac. I thought there must be a windoze thing that does the same thing, I searched and found this post on SourceCraft Blog where the author talks about setting up autotest with Snarl (for windoze). I tried my darnest to get it to work on windoze and popup a snarl message (like you cool mac kids with your growl notifications) .. and there's a bug somewhere because it says every time 100% tests pass..and I know I'm not that good. Haven't worked on it in awhile though, so I should try again I guess (or get a mac, which I am trying to do!)

rcov - one project I was working on went pretty fast (one danger of doing Rails for people that are used to "other" languages) and I was accused of not making quality code! so I installed rcov and showed them my 100% test coverage. I know rcov doesn't tell you how "good" your code is, but it does tell you its well tested. How about them apples? ok, I'm a smartass sometimes. ;)

The Rails Way - I was one of the technical reviewers for "The Rails Way" written by Obie Fernandez. It was a fascinating read and I learned a ton. I can't wait for the paper book to be printed, due out in October (The site says November, so maybe I am mistaken on October). If you do Rails -- get the book! I'll post a more detailed review when the book is out.

PeepCode.com - I've been an avid PeepCode.com fan from the first screencast I purchased -- about REST. I watched the episodes on TDD and the two about RSpec. This was very helpful. See, one problem I find with learning rails stuff is that there are all sorts of blogs on something, and sure by picking up pieces here and there you COULD probably get the learning you would gain from PeepCode.. but with PeepCode, its all in one spot and you can SEE it works, which is key for me. There is alot to be said for "seeing" something work to solidify the process in your mind -- but everyone learns different so that probably doesn't work for everyone.

Watching the rails commits - Ok so maybe I need a life. I've been watching the rails commits every day and seeing what changed. Alot of clean up going on it looks like. One of these days (soon I hope), I'll test some of the patches or try to fix a bug.

Lots of stuff going on and I'm having fun.

I've been kinda on a rails spree lately, I guess I've had some free time and also redoing a rails 1.1.6 project (and was noob then and no clue of what I was doing) and updating it to use REST.

I got Geoffrey Grosenbach PeepCode's REST Tutorial, which is very awesome and well worth the 9 bucks. Its over an hour long! I also got the RJS Tutorial which is also awesome. I can't wait till payday to get the $40 pack so I can get some more! There's just something about SEEING something work that makes it stick sometimes.

Also I spent some time on Railscasts which features a ton of short demos on rails topics. Very cool. In particular i liked Testing Without Fixtures which is cool because sometimes fixtures are a PITA!

When watching one of the PeepCode screencasts I saw him using "autotest" .. a cool toy which I must have too! I searched for it and found this posting on his blog. Now I'm autotesting all the time :) It basically monitors your rails site and runs the test everytime you change your code.

I've been using e-TextEditor and slowly learning the shortcuts. I love the font that was on PeepCode's screen cast and found a link on the PeepCode FAQ where I can download it. For Free! And it mentioned the name of the theme used in Textmate -- which happened to be the one I had found in e-Text-Editor and was using. No wonder I liked it! I also used this font in my Putty settings and changed the awful default colors (esp that dark blue! hard to see!). e-TextEditor is in Beta but its in great shape and i was so happy to see a "close all tabs" feature put into the latest build. I'll be ecstatic when they make a linux version.

I was starting a redo of a old (rails 1.1.6) site and thought I'll store the rails in the vendor directory so I don't have to worry about what version is installed in the server, so I looked up this nifty Article on SitePoint where they explain how to do that. Installing and Managing Edge Rails.

I started with some basic steps to "redo" my old site.. used the controller generator.. whoa.. huh? ".html.erb" .. I instant messaged a friend, Carmelyne and said whats up with ".html.erb" .. she is like, oh thats edge rails. I thought I had installed 1.2 release instead but on closer inspection I did indeed install edge. I must have had the version number wrong or something. Doh, oh well.. let me try it anyways.

In further discussion.. she suggested i look at using REST.. "isn't it just for webservices?" i ask, she said no. I'm not doing anything that I will need to publish web services for.... its just a bakery order site. But, I did a little research and Carmelyne pointed me to some resources.... and I got it!

A lightbulb went on!

I used the scaffold in edge to build my model... looked at the controller...looked at routes.rb ... and i got it. :)

Read these to understand what the heck I am talking about:
A Series of 5 articles on REST and Rails - very basic and helped me understand how, what why of REST and Rails.
REST on Rails - another good one

I feel like I've been a bird with my head in the sand. I'd read stuff before but never understood how, what and why of REST.

More to follow as it sinks in.

Next Page »