posts by date

03/2007
Rails tips and tricks, part 3

One thing I really hate about Windows development is no terminal. I love the command-line, and while there exists one or two substitutes, it’s still a far cry from the real terminal. The Mac terminal. Despite my bitterness, most, if not all, of these tips concern the command-line.

Subversion integration

When I first started using subversion, rather than jumping right in with tortoise, it was recommended that I become familiar with the svn commands. Since I’m somewhat partial to the command-line, that’s what I did. In fact, that’s all I do.

One thing that quickly annoyed me was having to do an svn add whenever I generated something (model, controller, migration, etc.) That’s when I found use in tortoise, to easily view all non-versioned files. Then I learned that you can pass the --svn option onto the end of any “generator” to automatically do an svn add on those new files. Oh, and it works for script/destroy, too. Sweet.

## will also add files to subversion
$ ruby script/generate model Project --svn

## will also remove files from subversion
$ ruby script/destroy model Project --svn

## FILES AFFECTED:
 #   1) project.rb             - the model itself (in app/models)
 #   2) project_test.rb        - unit test (in test/unit)
 #   3) projects.yml           - project fixture (in test/fixtures) 
 #   4) XXX_create_projects.rb - migration (in db/migrate)

It works with all generators, including your own.

Console: interactive application

The console is a good place to quickly interact with your application. In fact, did you know your entire application is actually tucked away in an object, waiting to be woken up from the console? Here’s some of the things you can do:

$ ruby script/console
>> app.url_for :controller => :public, :action => :about
=> "http://example.com/public/about"

>> app.get("/public")
=> 200
>> app.get("/ryan")
=> 404

# others include
>> app.response.headers
>> app.response.body[0,75]
>> app.post("/collection/add/1")
>> app.response.redirected_to
>> app.follow_redirect!

# fix errors in your code, then...
>> reload!

Pretty straight-forward.

Console: setting a default object

If you’re going to be interfacing with your “app” object a lot (or any object for that matter), it may be worth it to set it as the default.

>> irb app
>> get "/public"
=> 200
>> get "/ryan"
=> 404
>> exit

# now you're back to normal
>> 

Console: routing

Routing can get tricky, and sometimes you need to stop and quickly double check that it’s all working properly. Well, by setting the default object to the Routes class, you can quickly analyze your routes.

>> irb ActionController::Routing::Routes
>> puts routes
ANY  /                                    {:action=>"index", :controller=>"public"}
...
ANY  /:controller/:action/:id.:format/    {}

# independently play with paths
>> recognize_path "/about"
=> {:controller=>"public", :action=>"about"}
>> recognize_path "/public"
=> {:controller=>"public", :action=>"index"}

# or check a path inversely
>> generate :controller => "public", :action => "about"
=> "/about"
>> generate :controller => "public", :action => "index"
=> "/"

And on and on. The console is awesome, really, and I don’t use it near as much as I should. I just wish I had that Mac terminal.

Insane dice stacking video

Random videos on YouTube are often nice when taking a small break from reading and writing code. Sometimes it’s good to blink, too, so your contacts don’t glue themselves to your eyes, like mine have done the last couple of days (I should just go back to glasses). Jeez—talk about side-tracked. I stumbled upon this stacking dice video a little while ago, and it’s just ridiculous. It’s almost as if it’s magic. Some people have such odd talents.

Posting drought

I haven’t had much time to post anything for the last few days, but it seems like I’m not the only one. All of the sites I normally read have been laying low lately, and my other feeds have slowed down a good bit, too. Honestly, I don’t really feel like writing anything. I have a few things that I could post about (and normally would), but I’m just not in the mood. And that could just be my reaction to the lack of posting that has been shading the internet lately. Maybe everyone else simply isn’t in the mood to post, either. Or maybe the internet is finally dying. Or maybe, like I said, I’ve just been too busy. Oh well—I suppose I’ll snap out of it in a day or two.

RSS aggregator in 26 lines of Ruby

Ruby is awesome, but we already knew that. Leveraging the libraries in Ruby can be well worth the effort. Here’s a case where four Ruby gems were used to write a simple RSS aggregator, in 26 lines of code mind you:

Pretty impressive, I think.

Ruby on Rails screencasts (for free)

I came across some Ruby on Rails screencasts the other day. They appear to be short and sweet, and the topics are all good things to know. Apparently the site is updated quite a bit, too (8 movies between March 5-21). And the best part: they’re free.

Typography reference from SXSW 2007

Typography is really interesting to me, as well as inspirational. Whether or not I employ all of the things I’ve read is a topic for a different day; but there’s nothing wrong with having a few good references. Not that I was there, but at SXSW 2007, there was a presentation titled, Web Typography Sucks (which is yet another reason to use Textile). The authors have put together a nice collection of references (including their presentation):

Those are some of the best articles I’ve seen on the topic. So bookmark it if you’re at all interested. I was hoping to make it my entire life as one of those to not post about conferences, but since I’ve already blown that, I figured one more wouldn’t hurt.

Render an update or use RJS?

There’s a part of me that doesn’t like to use render :update in my methods, as I like to keep all of that view stuff, well, with the view stuff. But at the same time, I sometimes only need to update one thing on a page. Do I really need an entire file for this? And now that Chris showed me how to access view helpers in my controllers, that really alleviates the need for one-liner RJS templates. Which do you prefer?

## OPTION 1
## Thoughts: nice to have it all there, but is sort of inconsistent with MVC,
##           which could cause confusion for other developers looking for RJS

def display_name
  @person = Person.find(params[:id])
  render :update do |page|
    page.replace_html 'dom-id', @person.full_name
  end
end

## OPTION 2
## Thoughts: consistent with MVC, but it's hard for me to have one line in RJS

def display_name
  @person = Person.find(params[:id])
end

# display_name.rjs
page.replace_html 'dom-id', @person.full_name

Personally, I do both. Is that right? I often find it difficult to answer the question, “Why didn’t you use RJS there?” I end up saying, well, because it’s only one line. But I’ve also used render :update with two lines, and three lines. And on the contrary, I’ve used RJS with one, two, or three lines. I guess I’m just looking for a balance.

I’d like to be consistent and just use one or the other. It strikes me as odd anytime I open a RJS file and see one (or so) line(s). Which is the best practice? Which do you prefer?

More Flickr pictures worth viewing

I realize not everyone likes to browse Flickr, but I do. I’ve posted about a nice Flickr gallery before, but I’ve found a couple more worth mentioning.

  1. http://www.flickr.com/photos/valpopando/
  2. http://www.flickr.com/photos/rebba/

The first heavily uses HDR, which is an editing technique used to, essentially, bring a photo to life. It basically increases the difference between light and dark, by using several different exposures of the same image. Part of me doesn’t want to get into that, as I’ve played with Photoshop a lot, and I’d rather not edit images outside of what can be done on the camera—for now, at least.

The second is (from what I’ve read) the most viewed user on Flickr. She’s an award-winning photographer. If you’re not planning on viewing either of the above galleries, at least check out her freeze! set.

Add a loading image for all ajax requests

Do you get tired of passing the :loading and :complete options to your link_to_remote’s? Me too. I usually keep some sort of ‘loading’ .gif in my layout somewhere, and set it to show/hide on each ajax call. I stumbled upon a solution using event:Selectors the other day, and it worked like a charm. You may be able to register ajax responders directly in your prototype.js file, but from past experience I’ve found eventselectors.js to be useful, so having it handy isn’t so bad.

Mandatory customer service

Or, in other words, customer service via mandatory services. I’ve been struggling with Direct Loans in order to get a recent payment to apply to a specific loan (which I was told I could do, by Direct Loans). I won’t go into the details, but basically an unsubsidized loan found its way into my balance (they accrue interest from the moment you get them, rather than starting 6 months after graduation). I decline every single one, but nonetheless, I have one. So I made a payment to get rid of it, as well as the interest it had gained. That payment was made on January 23, 2007. Guess what? I still have that unsub loan balance, along with more interest. Anyway, it’s been 5 phone calls and 6 emails later, and it’s still there.

Somewhere along the “submit a payment to a specific loan” path, there is a flaw. And while they act like they care, they don’t. Because they know I don’t have a choice in the matter; it’s officially out of my hands. All I can do is keep emailing and calling, only to hear “we will re-submit the request” each and every time. It’s no different than any other service that ultimately leaves you with no choice but to suck it up. Take the Post Office, for instance. They can be as rude as they want to be, but you still have to stand in the line extending 100 feet because they are the only one’s who can mail your package. Sure, you could leave, but where does that get you? Irritated with a package that didn’t get sent.

These attitudes and inefficiencies may not always be intentional, but there’s definitely no effort (or incentive, really) to fix them. Either way, I still have to pay my loans back plus interest, and I’m sure I’ll be standing in that Post Office line again. Oh well, I suppose—there will forever and always be annoyances with customer service.

Did you know?

I stumbled across a video tonight before going to bed, and although it’s 6:06 minutes long and 1:30 AM, I couldn’t stop watching it. It’s interesting, but disturbing at the same time—check it out if you get a minute:

Devoting shared RSS to photography

I like to somehow mark interesting things I read. Whether it’s via del.icio.us or a Google Reader star, I save interesting/helpful posts, thinking I might need or want it some day. The problem I have with starring feeds is I’ve starred so many that, in the event I should need something, it becomes somewhat overwhelming to find. Devoting stars to one concept cuts the benefit down to about 5%, so that doesn’t work, either. I know this is the exact idea behind tags, but I find I sometimes tag inconsistently (‘photography’ vs. ‘photos’ vs. ‘photo’ vs. ‘flickr’).

Google Reader has this nice little feature known as “sharing” that I’ve yet to use. Actually, I never had a reason to use it. And maybe I still don’t have a reason, but it’s stupidly simple, so why not. As you may know, photography is increasingly taking over my interests. Sharing items may be a reasonable way to keep track of all the interesting/helpful posts related to photography.

If you’re at all interested in photography, you can catch all of what I consider to be “golden nugget photography posts” via my shared items page. Oh, and there’s a feed for my shared items as well (shared items RSS). The site itself is somewhat useless, as you can’t search it or easily access older posts, so the feed is probably the way to go. But it’s a place for me to see valuable photography posts inside of Google Reader, which is kind of nice.

Flickr just got perfect

Flickr is probably my most favorite web application I’ve ever used (“most favorite” doesn’t sound right, but you get the idea). Now that I’m really getting into photography, I’m realizing more of what it can do—which results in me loving liking it more and more. Then today (or maybe yesterday), Flickr released collections and a customizable layout. A collection is nothing more than a ‘set of sets’, but this is something I’ve been wanting for a long time. Now, not only can I organize my trips and vacations into sets, but I can have a collection of sets for Trips & Vacations.

The fact that you can associate a few sets with a collection isn’t that impressive (although very beneficial), but the way they’ve implemented it is impressive. The ‘organize’ section of your photos is where you can setup collections. Just drag your sets over to the collection of your choice, and viola, it’s that simple (you can also drag/reorder your sets within the collection itself). Then you can create a mosaic for that collection, choosing a nice blend of 12 photos from any of the sets it contains (those are also draggable). I think that’s awesome, and it works really well.

And to add in a little more, you can now specify a different layout for your main photo page. You can have small pictures with sets to the right, or small pictures with collections to the right, or large pictures with sets to the right, so on and so forth. There is a total of six layout options. I personally like having smaller photos with my recent sets to the right—the default view. But when I get a new camera, I’m sure I’ll be taking pictures at least 2-4x more than I am now, so I might decide that collections to the right would be a better fit. Either way, it’s nice to have the option. Kudos to Flickr for being perfect.

Extending my view, literally

In late September, I finally got a new computer at work (I was using my personal laptop before that). Despite what some people would say, it’s a pretty nice Dell with a 19” ultra sharp flat panel. I’ve always been a sucker for space on the screen (I keep my laptop resolution at ~ 1900×1200). Well, it was decided that I could get another 19” flat panel, you know, to spread things out a bit. So here’s what I see now:

I didn’t know having dual monitors would be so nice. There’s something about never having to minimize my code that makes me more productive.

Navigation helper acting weird

The I’ve handled tabs in the past has always bothered me. I’m trying to handle them a different way, now that I have better options. Just like anything you do the first time, I’m sure this could be improved upon—but here’s what I have:

# application_helper.rb
def main_navigation(links)
  li_class, link_class = 'left', 'non-current'
  nav_bar = Array.new
  links.each do |link|
    li_class = 'right' if controller.controller_name.downcase == 'settings'
    link_class = 'current' if controller.controller_name.downcase == link.downcase
    nav_bar << "<li class='#{li_class}'>#{link_to link.capitalize, '/' + link.downcase, :class => link_class}</li>"
  end
  nav_bar
end

I’m calling this helper like this:

# layout
<%= main_navigation ['dashboard','messages','settings'] %>

Yes, each link does correspond to a controller, and the reason I’m changing the ‘settings’ tab is because I want it off to the right, separated from the other tabs. The concept is obvious, but this thing is acting crazy. Here’s what happens when I click…

  1. Dashboard—All three list items have class='left' and each tab has class='current'
  2. Messages—All three list items have class='left' but this time, the Dashboard tab has class='non-current'
  3. Settings—All three list items have class='right', and only the Settings tab has class='current' (which actually is the current section, making it the only one to follow the ‘current’ rule)

It seems like the li_class always applies to all three tabs, but the link_class doesn’t. Is there something blatantly wrong with this?

UPDATE—the only trouble I’m having is with the ‘left’ and ‘right’ settings. All tabs are left if I click on Dashboard or Messages, and all tabs are right if I click on Settings. I had the li_class and link_class being initialized outside the loop, like an ignoramus. But I can’t seem to get the settings tab to be the only tab with class='right'.

It works both ways, doesn't it?

Numerous times today, I’ve heard things like “I sure do miss that hour of sleep.” I don’t really get that. To me, it’s only a problem the day the clocks are changed. I should start replying by saying, “Yeah, but doesn’t that mean you really went to bed at 10:00 PM instead of 11:00 PM?” Then maybe I would realize their logic. Daylight savings doesn’t only apply in the mornings. Personally, I feel just as tired if I get up at 7:00 AM or 6:00 AM. For me, it’s fighting the snooze and taking that first step regardless of what the clock says.

Programming in Ruby is like writing

Mark Twain once received a telegram from a publisher that read:

NEED 2-PAGE SHORT STORY 2 DAYS.

Twain replied:

NO CAN DO 2 PAGES 2 DAYS. CAN DO 30 PAGES 2 DAYS. NEED 30 DAYS TO DO 2 PAGES.

As his reply implicitly states, there are difficulties associated with short and concise writing—it’s not easy. I agree wholeheartedly. I think this same type of reality exists while programming in Ruby. I can get something working really fast, but (for me at least), it seems like I keep wanting to extract and refactor until the method is as small as it can possibly be. I could probably spend days trying to out-do my current code and get just as much satisfaction as if I were developing something new. I love how much you can do with one single line in Ruby. It’s motivational.

And for the record, I don’t apply the short and concise writing methodology here (obviously). This site just isn’t that sophisticated. But I can see the challenges and fun in that, too.

Filtering parameters in your log files

Log files are good for figuring out what went wrong, or what SQL statement was executed, and many other things. But they’re terrible for storing sensitive information (such as passwords, credit card numbers, etc). Luckily, there’s an easy way to filter out the parameters you want to keep safe: filter_parameter_logging.

Here’s all you have to do:

filter_parameter_logging :username, :password

## Here's what ends up in the .log file
 # Parameters: {"action"   => "login",
 #              "username" => "[FILTERED]",
 #              "password" => "[FILTERED]"}

Just stick that in any controller you want to protect. What’s really nice about this is if the arguments match any part of the parameter key, the value will be filtered.

filter_parameter_logging :password

## Matches:
 # params[:password]
 # params[:user][:password]
 # params[:user][:login_password]
 # params[:user][:login_password_field]
 # ...

You can also pass a block to declare the filter yourself. So instead of using the regular expression matching, you could do something like this:

filter_parameter_logging do |key, value|
  value = "[can't see this]" if value == "password"
end

It’s just a really easy way to add a little more protection to your sensitive data.

Awesome tool for beer estimates

I am far from the party animal; in fact, I don’t drink at all. But I came across The Kegulator and thought I’d share. A good design, good interface, and if it’s anywhere close to accurate, I give it a thumbs up.

A snowy and dangerous day

I didn’t go to work today. I woke up with full intention to go, but the traffic out front was backed up and I assumed it was because of the weather. I walked outside and took a few pictures to capture the mess; it’s much easier to just show those than try to explain how bad it really was. I made a set on Flickr:

I’m not too fond of snow (because I have to commute in it), but solid ice on a really steep hill is much, much worse.

2008 by Ryan Heath | Get In Touch

flickr

DesolateInfinityLooking upDazedBlurred