Ruby


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!

Its been a crazy December through January and I haven't written much!

I'm glad the GWT posts helped some of you from the comments. I spent some time on figuring them out from the limited docs on google's GWT site, mostly I think it helps to have complete examples since they dont make it real clear what file each snippit of code goes in. I'm glad the pain I went through to figure them out help some of you :) A few of you had problems but i haven't gotten around to seeing what is wrong. I was using the trunk version of GWT, so if you are using 2.0 then you might have some differences.

I've been diving my head back into rails after spending a spell in perl/mason and GWT in some projects for work. I think other languages are neat but I really love ruby. So I've been re-watching some of my episodes of PeepCode.com and RailsCasts.com those guys are awesome. I love this stuff. Why else would I be spending my Saturday night with Ruby vs watching a movie or playing a game!

I've also been playing with android a bit, its pretty fun to see my app on a phone! Working on a TODO List app, which seems almost like "hello world" but it has a twist... more later when i have something to show.

Been working learning jQuery. I had seen it before, but saw class names mixed with programming and having a ugghhhh feeling. But.. I decided to give it a shot and dang! I would have given my right arm to have this 5 years ago when i was experimenting with ajax (though it wasn't called that...) with setting the src of a script tag with a php url to load and save data. Anyways, its cool and neat. I think the name is horrible since you aren't really quering anything... IMHO :) Maybe if I can think of a better one I can suggest it, but seems like it is here to stay since there are stay since there are 4 books already about it!

To help with reviewing ruby I have been working through Ruby Koans. Hats off to EdgeCase. I have already written them and thanked them! This goes along with my post How To Get Better At Programming where I wrote about how i was working at getting better at programming. It all comes down to practice! ... I think when I finish the rubykoans exercises, i will revert and start going through them again. Almost like doing pushups every day (I push up to get more coffee at least 3x a day!).

Git ... I did my first pull request on github, very cool how that works.

Have some ideas for some more substantial posts... coming soon :)

I've have been pondering in the past 6 months - How do I get better at programing? What is the best way? do I need more books? At my current company, we whole heartedly engage in peer reviews, nothing gets checked in the repository without at least one person going over it. In that process, i've learned more about coding then I could from 10 books. I used to be a book fiend. I had about 10 books on every subject. Did I learn? yeah, some! But I think I've learned more from doing and practice. Practice, practice, practice! When the Chicago Ruby User Group offered this book in exchange for a review, I jumped at the chance.

“Refactoring in Ruby” written by William C. Wake and Kevin Rutherford.
Published by Addison-Wesley

"Refactoring in Ruby" is more like a "workbook" then a "how to write awesome code" book. If you download the code from github http://github.com/kevinrutherford/rrwb-code you have tests already written for the exercises.

The book is arranged in three parts, The Art of Refactoring, Code Smells, and Programs to Refactor.

There are explanations of "code smells" which are one characteristic of code that could be improved. Some of them are long parameter lists, unnecessarily complex, global variable, feature envy sections, etc. One thing I find interesting is the "How did it get this way?" section. It gives some insight into the thought process and reasoning behind the smell. I think this is good, as programmers our ego may be rather miffed to hear "This code stinks" but with some reasoning, it makes the pain less and I think firms up in our minds when this happens again, to do it this other way. I always want to know why when someone says I could do such and such thing better.

In addition to the code smell examples there are three programs to refactor in the end of the book. In a conversational tone, it walks through and gives some hints on what needs refactoring. Its almost as if you had a pair programming buddy working with you and identifying in small chunks what can be improved. This is definitely something I want to work through more carefully.

What I find odd, is that not all the code smells have code examples. The inspiration for the book I think is the Martin Fowler book "Refactoring Improving the design of Existing Code" which has examples for every code smell. Maybe Ruby smells less than Java? Or those fixes are really trivial? I don't know. Overall, this is a great book and is certainly worth the price and investment and you will be a better programmer because of it!

There are explanations of "code smells" which are one characteristic of code that could be improved. Some of them are long parameter lists, unnecessarily complex, global variable, feature envy sections, etc. One thing I find interesting is the "How did it get this way?" section. It gives some insight into the thought process and reasoning behind the smell. I think this is good, as programmers our ego may be rather miffed to hear "This code stinks" but with some reasoning, it makes the pain less and I think firms up in our minds when this happens again, to do it this other way. I always want to know why when someone says I could do such and such thing better.

In addition to the code smell examples there are three programs to refactor in the end of the book. In a conversational tone, it walks through and gives some hints on what needs refactoring. Its almost as if you had a pair programming buddy working with you and identifying in small chunks what can be improved. This is definitely something I want to work through more carefully.

What I find odd, is that not all the code smells have code examples. The inspiration for the book I think is the Martin Fowler book "Refactoring Improving the design of Existing Code" which has examples for every code smell. Maybe Ruby smells less than Java? Or those fixes are really trivial? I don't know. Overall, this is a great book and is certainly worth the price and investment and you will be a better programmer because of it!

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!

Call me crazy, but this is why I classify myself as a language geek. When I learn something fascinating, i wonder hmm how can I do that with X language? My last post I did an example of the Builder pattern as described in Effective Java by Joshua Bloch. The main motivation for me to use Builder is to have flexible parameter lists, without worrying about order of parameters (there are a few other reasons outlined in the book, but this is what I find cool).

Its too easy.

My class:

RUBY:
  1. class Address
  2.   attr_accessor :street, :street2, :city, :state, :zip, :address_type
  3.  
  4.   def initialize(&block)
  5.    
  6.     #set default values
  7.     self.city = "Chicago"
  8.     self.state = "IL"
  9.    
  10.     #set value from block
  11.     instance_eval &block if block_given?
  12.  
  13.   end
  14.  
  15. end

And the usage of it:

RUBY:
  1. def testDefaultValues
  2.     myaddress = Address.new
  3.     assert_equal("Chicago", myaddress.city)
  4.     assert_equal("IL", myaddress.state)
  5.   end
  6.  
  7.   def testStreetStateZip
  8.     myaddress = Address.new do
  9.       self.street = "this is the street"
  10.       self.zip = "11111"
  11.     end
  12.     assert_equal("Chicago", myaddress.city)
  13.     assert_equal("IL", myaddress.state)
  14.     assert_equal("this is the street", myaddress.street)
  15.     assert_equal("11111", myaddress.zip)
  16.   end

Wow, huh? Compare to

JAVA:
  1. public void testBuilderDefaults() {
  2. Address expected = new Address.Builder("Chicago", "IL").build();
  3. assertEquals("State is IL", "IL", expected.getState());
  4. assertEquals("City is Chicago", "Chicago", expected.getCity());
  5. }

then the optional params are chained to that:

JAVA:
  1. public void testBuilderStreetStateZip() {
  2.    Address expected = new Address.Builder("Chicago", "IL").street("this is an address").zip("11111").build();
  3.   assertEquals("this is an address", expected.getStreet());
  4.   assertEquals("11111", expected.getZip());
  5.   assertEquals("IL", expected.getState());
  6.   assertEquals("Chicago", expected.getCity());
  7. }

Full source for Ruby (though I was able to paste it all here!)
Address class in ruby | Address test in ruby

And for Java, if you want to compare ...
Address class in Java | Address test in java

Yes... sometimes its hard not to gloat. :-D

yeah yeah yeah, its not really "fair" to compare strongly typed languages... but as I said, my motivation is to have easy parameter lists without having to remember specific ordering of params for constructor or use multiple set methods.

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...

This book is still in beta, but so far... I love it!

Chapter 1 is a very brief overview of RSpec and Cucumber and in Chapter 2 you are shown some examples. This is Real Code That Works! You can type it in and run. That is awesome, I was so excited last night that I almost couldn't stop and go to sleep (Doc tells me to get more sleep. BAH!). I've done RSpec on a fairly large project before, a few years ago. I had seen some presentation at the Chirb meetings about some kind of testing involving Stories and Scenarios. It was interesting then... I just wasn't sure how you can translate that into code. Now I see, it looks like this method has matured to the point where it is viable. Cucumber is only version 0.3.11 at this time but hey! Its cool, its tight, its gonna take off!

Chapter 3 - Starting off with a game example! WAY TO GO! Nothing more uninteresting than Yet Another Bank Account or Blog example. This is totally awesome. Its a very conversational at first, as you are learning how to apply the "Story" concept to the need. Once the planning is out of the way.... its time to code!

Chapter 4 - Cucumber, Writing steps to the stories

Chapter 5 - RSpec, writing rspec tests

Its great to see code that you can type in an run and its kinda fun, it a game! what isn't fun about that! Great book so far Dave Chelimsky, Dave Astels, Zach Dennis, Aslak Hellesoy, Bryan Helmkamp and Dan North. Right on! Looking forward to the rest :)

Next Page »