Resources For Rails Development in Vim

While most programming languages seem to take steps toward big, full-featured graphical IDEs, Rails development seems to have gone the reverse: back to the command line, command line editors, and minimalist interfaces. Today, I’d like to share with you several resources that I’ve used to streamline my development process.

TextMate (€39) — Considered the definitive text editor for OS X, TextMate is a worthwhile purchase for any developer using any language. It’s extensible, powerful, and, Rails-specifically, allows for easy navigation between your MVC layers with easy hotkeys. If you code on OS X, you owe it to yourself to buy this.

The Playbook (free/$15/$50) — If you’re looking for tips on how to start a web design firm, set up your development environment, do proper project management, and more, consider picking up a copy of The Playbook, an eBook written by the geniuses at ThoughtBot. ThoughtBot is known for several of their Ruby gems that have been released into the public domain, including high_voltage, clearance, suspenders, and more. They are also known for some of their hugely popular applications, including Airbrake and Trajectory. They offer a few free snippets, a single user license, and a group license.

Rails.vim (free) — While Vim is an amazing editor on its own, it thankfully allows for plugins to be written to extend the functionality. Written by Tim Pope (Twitter/GitHub), Rails.vim is an amazing plugin that adds a whole host of commands to the editor, allowing for more fluid Rails development. Best of all, it’s free, open source, and readily available on our favourite source control repository, GitHub.

Vim for Rails Developers ($15/$50) — Vim is considered one of the most powerful text editors out there, and it’s available on virtually every platform. That being said, it’s a dauntingly steep learning curve (although I wrote a guide on getting started with it), and every bit of help you can get is worth it. This 34 minute video gives you the rundown of using rails.vim along with your Vim install. As with The Playbook, a single user and group license is available.

RailsCasts (free/$9 per mo) — Probably the go-to for most Rails podcasts, Ryan Bates (Twitter/GitHub) has been churning out 2 podcasts about Ruby on Rails for years now. He explains topics clearly, pushes the limits of what gems can do, and always offers comparisons between similar gems. Most of his content is free, but Pro users ($9/month) get access to Pro episodes which cover more content and new gems.

First Tinkerings with Arduino

A couple months ago, I finally got around to picking up an Arduino and an ethernet shield. These little development boards are a nice way of tinkering around with ATMega chips and to try your hand at writing lightweight C++ code for embedded systems.

I’ve always wanted to try programming on an embedded system; being able to run a small (really small!) computer off of a small pack of batteries is pretty cool! I also wanted to use ATMega chips along with a whole slew of sensors as part of my home automation project as a means to collect data from various rooms in the house without having to run more than a single network cable to a room.

Because I’m a cheap son-of-a-bitch, I bought not from a reputable retailer, but from your typical Chinese knockoff website with free shipping. On one hand, I’m really happy with my purchase, since the Arduino works as expected, and it cost me quite a bit less than SparkFun. On the other hand, I accidentally purchased an ethernet shield that was incompatible with the standard Ethernet libraries, and thus had essentially purchased a small, lightweight brick. No worry; I simply ordered one that worked with the library.

The goal with these Arduinos is to set up a small HTTP server on each one and connect a bunch of sensors, such as temperature, humidity, carbon monoxide, ambient light, and possibly others. A central server will poll the Arduinos for data at set periods of time, and then that data will be collected, aggregated, and analysed for the user to view. Ideally, this would eventually be used to tie into X10 (or similar) systems to help balance the temperature in rooms, turn off lights when people aren’t in rooms, or warn of deadly gases.

Now, if I ever get my ass in gear on this project, I might actually have something to show for it!

Rails 3 Generators: Adding Migration Templates

I’ve been working on some really cool projects using Ruby on Rails recently, but I found myself duplicating code across them. Obviously, that doesn’t make sense to me, even when the code bases are different, so I decided to start extracting some of the logic into Ruby’s awesome gem format. Rails 3 has awesome gem handling, if I’ve found uses for some of these pieces of functionality across multiple projects, then others may as well.

The first gem I’m working on stems from this post from a couple years ago where I demonstrated how to do dynamically-named routes using semi-static pages. This approach was different than ThoughtBot’s high_voltage gem because it stored the page content in the database rather than as files in the database deployment. I have an issue with that implementation because I’m a firm believer that you shouldn’t have to deploy a new revision of your software just to update a bit of content; it should be controllable from the user interface as part of our regular CRUD routine.

My first struggle with the creation of the gem was writing a template for the migration. I had some trouble with these two errors coming up:

  • 1
    undefined method `migration_template' for #<Semisonic::InstallGenerator:0x000000040899c8> (NoMethodError)
  • 1
    `next_migration_number': NotImplementedError (NotImplementedError)

Maybe my Google skills have been slipping, but I had trouble finding a ‘fix’ for these. So, here’s how to fix the above errors if you ever get them:

  • If you get the first error (undefined method ‘migration_template’), you’re missing an include in your class. Add “include Rails::Generators::Migration” on the first line of your generator class, and you’re good to go!
  • If you get the second error (‘next_migration_number’ not implemented), you’ll need to implement the method ‘next_migration_number’. The following code snippet should work just fine for it:
    def self.next_migration_number(path)
      unless @prev_migration_nr
        @prev_migration_nr ="%Y%m%d%H%M%S").to_i
        @prev_migration_nr += 1

Hopefully those two fixes help somebody else out.

My Commitment To The Web Design World :: A One-Month Challenge

After reading an article on Smashing Magazine (link to the article is here) that talked about the state of the web design world right now and where it’s progressed, it really got me thinking. The article mentions that the number of experts in the field has not grown proportionately to the number of developers, but the number of inexperienced people giving advice (often wrong!) has grown exponentially. There isn’t the discussion there used to be, and the sharing of knowledge seems to be lacking.

Thus, I have issued myself a one-month challenge:

The Challenge

Contribute to the web design world at least once per day for a whole month.

The Rules:

  • I need to perform 30 contributions over 30 days, not necessarily 1 per day (I have a life, or at least I like to think that I do)
  • Contributions can be:
    • writing articles on my blog
    • offering small tidbits of code that I believe would be of some use to others
    • provide meaningful comments on web design articles
    • tweeting about other well-written things that better the community
    • answer questions on sites such as StackOverflow, Quora, etc
    • review of a number of similar products

It Starts Today

My contribution today comes in the form of this blog post, and is a request from every web designer out there who reads this.

If you read the article and agree with what it says, take up your own 30-day challenge. Tweet this blog post, write about it in your blog and link me for a pingback, write me a comment, do whatever you can to get the word out. The evolution of the world’s web design community begins with every single regular developer striving to offer something to the rest of the community. I hope this blog and the above article will inspire even one or two people to do the same as I am.

Dynamic Named Routes for Semi-Static Pages in Rails

When I was designing the new UMSwing website, I had a few issues that, at the time, I didn’t have a clean method of implementing. One of those was the creation of semi-static pages. After watching this episode of Railscasts, I had a pretty good idea of how to implement them. The only issue with the solution offered was the lack of dynamically generated routes.

Semi-static pages are used everywhere on websites. They’re those pages like an “About” page, which has content on it that doesn’t really change that often. Typically, a controller would have to house these actions (/about, /faq, /contact, etc.), and  the routes specified manually. Railscasts came up with an ingenious idea to create a controller which was routed to /static/*, so that semi-static pages could be created on-the-fly and modified easily. It also allows for modifications to change without committing to a repository and going through the process of deploying all over again.

For those needing a quick Rails primer before going on, here’s the quick and dirty of what you need to know to understand this:

  • Rails is a MVC-based web application framework that runs on Ruby. In short, Ruby code is written to create webpages on-the-fly.
  • Every request in Rails is first put through the routes file in config/routes.rb. This file tells Rails which Controller and Action is run.

Okay, let’s get started. Let’s create our static pages scaffold (which includes model, views, and the controller). Obviously, there are sections of this that you would want to require authentication for (editing and deleting, for example), but that’s outside the scope of this tutorial.

script/generate scaffold pages title:string permalink:string content:text;
rake db:migrate

Now we need to modify our controller slightly. More specifically, our show action. Right now, it will respond to showing an element only when the ID is displayed. We want to modify it to handle a permalink as well (/about and /contact look better than /pages/135, don’t you think?). Here is your modified show action:

def show
  if params[:permalink]
    @page = Page.find_by_permalink(params[:permalink])
    @page = Page.find(params[:id])

Before we go any further, we need to create two custom methods in our model. These will format the permalink to remove any unwanted characters for the custom route name (replacing all unacceptable characters with an underscore) and for the URL (replacing all unacceptable characters with a forward slash to allow for nesting of pages). It’s also important to note here that previous validation should be done to ensure that the permalink does not have leading or tailing non-alphanumeric characters, but I removed that for simplicity’s sake.

class Page < ActiveRecord::Base
  def route_name
    p = self.permalink.gsub(/([^A-Za-z0-9])+/, '_').downcase # Change non-alphanumeric characters to an underscore
  def uri
    self.permalink.gsub(/([^A-Za-z0-9])+/, '/').downcase # Change non-alphanumeric characters to a forward slash

At this point, we can create and modify our pages as we would regularly expect from a new controller. All of our pages are accessible via /pages/1, /pages/2 etc. We now need to make our controller act as our catch-all (so that all requests that do not match any of the other controllers get routed to our Pages controller), and we also need to provide permalink support. Finally, we will dynamically generate customized, name routes for all of our semi-static pages. All of that gets accomplished with a few short lines of code. Add the following code to the top of your config/routes.rb file, starting at line 2 (inside the ActionController::Routing::Routes.draw section):

def map.static_page_actions
  pages = Page.find(:all)
  pages.each do |page|
    self.send("static_#{page.route_name}", "#{page.uri}", :controller => "Pages", :action => "show", :permalink => page.permalink)

Finally, we need to call this method close to the bottom of the code, right before our default catch-all routes.

map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'

What this method does is retrieve all of the static pages in the database, then creates a customized, named route for each page, telling Rails what each URI should look like, and where to direct the request to.

Hopefully this helps some people out with their dynamic page creation. I’m pretty sure there’s a pitfall or two here, but I think it could be taken care of by doing some simple route housecleaning in the Pages CRUD controller. The perk of this option is that it allows the routes to be named, and hopefully that is of some benefit for others.

5 Goals For The Next 6 Months

Well, in an attempt to get back on my ‘writing horse’, I figured I’d start with some of the things that are rattling around my brain right now in terms of what I want to get accomplished in the short term. Some are computer-related, others are not. Nevertheless, I have some goals for things that I want to get done or accomplish in the next 6 months. Here are five of them.

1. Buy a new car

With the potential of a great new job headed my way (possibly more on that later), I should have some disposable income in the near future. To celebrate this, I think it’s time to get a new car; my current car, although it holds 5 people, is hardly what you consider sporty, is developing a bad case of rust, guzzles gas like nobody’s business, and isn’t fun to drive at all. I plan on buying a 2003 Hyundai Tiburon with a 5-speed manual transmission. They come in around $9000 before taxes, so on a financing plan I’ll be able to buy that no problem.

2. Build a customized car trunk sound system enclosure

I’d love to put my DIY skills to the test and create a proper molded sound system enclosure for my new car. It’s a lot of work, but it’ll be a lot of fun. This will also be very useful to work on some woodworking skills and some custom fabrication work.

3. Start my development website

For about two years, I ran a security-based site, but eventually shut it down because my interests simply did not coincide with my interests and life aspirations. As such, I’ve decided to start a development-based website. I can do the security-aspect within the programming and development, but I can also get into graphics design. It fits into my interests much more at this point in time, and I think it will be more beneficial to the internet as well.

4. Develop Thimbleberry

I have a new site in the works with a friend. That’s about all I’ll tell you for now. Either way, should be a fun time.

5. Start actively contributing to the open source community

The open source community is amazing. Those of you that have heard of a little operating system called Linux may know that it’s open source. That’s right: it’s free to use, free to modify, and free to redistribute. There are tons of open source projects available online, and I’d like to start contributing to one or start a new one that people will actually use. I’ve been using open source software for a long time, and it’s about time that I gave back to the community that has helped me out in so many ways.

Well, it may be feeble, but it’s a start at getting back in the writing groove. Soon I’ll start doing a bit more technology writing again, and will hopefully do some stuff on interface design. Thanks for sticking with me through my creative drought, and we will hopefully see you Monday.

Random Post: A Programmer’s Desktop

Just for the heck of it, I decided that I would post a screenshot of my desktop right before I start programming (ie. before too many windows get opened and clutter my workspace). Those of you that are sharp might notice that it looks a little…wide. That’s because I have three monitors on my desktop — two 19″ and one 22″ LCD monitors. That gives me a total resolution of 4560×1050: far bigger than a single monitor could reasonably give me.

My Desktop

Extra brownie points go to those who can answer the following questions about the screenshot:

  • How many cores does my desktop have?
  • What music player am I using?
  • What scripting language server is running in the command line?
  • What is the symbol on my desktop, what is it’s significance, and who came up with the idea to use this symbol for this purpose?

Anyways, I have some new photos that will be going up tomorrow, as well as some of my experiences with using an off-camera flash. Stay tuned for that!

IPAM Presentation: November 2009

Last Wednesday, myself and the other co-op student working with me did a presentation to the Information Protection Association of Manitoba (IPAM) about attacks on web-based applications. It was certainly an interesting experience. Although it wasn’t a stellar performance, I think we did okay considering our presentation skills. Unfortunately we were expecting a slightly larger percentage of technical-minded people rather than business-minded people, and thus I got the impression that some of the talk was a little over the heads of a few of those in attendance. Regardless, it was a learning experience, and something I learned a lot from.

I was approached twice after our presentation was over. The first gentleman, to paraphrase, suggested that the presentation would be more useful had it included a mitigation strategy to prevent and (hopefully) eliminate the possibility of attack. I thought he might be on to something here. After all, wouldn’t it be great to have a check list to go through, and making sure each item is checked off would result in a secure application? For the rest of the day, I spent a lot of time going back and forth on this idea. On one hand, this check list would be nice, but I also firmly believe that a large amount of the prevention relies on the skill level of the programmer, debugger, and penetration tester, and a check list simply wouldn’t be sufficient to protect yourself from attacks. But, having the check list would be a good start. Sort of an “if you’ve done these things, you’ve covered the basics” check list. It would be a good reminder sheet for pro programmers, and a good stepping stone for those who are just starting off. To that person, your suggestion has been heard, and the check list has been added to my to-do list, hopefully to have a first draft out within a month or so, so stay tuned for that.

The second gentleman asked if the slides to the presentation would be online for later viewing. At the end of the presentation, although we took almost an hour, I was well aware that we were rushing; we probably had too much content that we wanted to cover. Before the presentation I had already planned to put the slides online as a reference; although it’s nice to see the slides during the talk, it’s also nice to go back and view them at a later date. Thus, my slides will be online here for anybody to take a look at. I will also be posting my source code, but that will be a bit later (ie. probably next week), since there’s a few sections that are a little finicky right now.

GNU Screen and Byobu Made Easy

For the *nix elitist, no graphical tool comes close to the power that the command line provides. While this may strike some people as odd, particularly those who only have experience with Windows, it’s a pretty well known fact that the Linux command line provides a method of controlling every aspect of your computer activity; this is so much the case that most GUI applications on Linux are just command line “wrappers”, hiding you from what’s actually happening behind the scenes.

GNU ScreenWhile this is all fine and dandy, things like development and multi-tasking can prove to be a little frustrating when connecting to a remote location and requiring more than one window open. Although a typical command line pretty much prevents this from happening, using GNU Screen or Byobu can make things a lot smoother. One window, multiple command lines.

As most developers will tell you, having multiple windows available to you is a godsend. It’s particularly useful when you have scripts to run in the background that generate output, but you don’t want to fork them as a daemon. Now, with GNU Screen and Byobu, you can do this easily, and even make your screen look snazzy as well. The only drawback to these utilities is that they are a little hard to get used to. In this post, I will quickly outline some of the key combinations which I use regularly.

GNU Screen and Byobu Simplified

The number one thing to remember about every command you use is Ctrl+A, which will be written as C-a. This is picked up by screen and will tell the utility that the next characters typed will be commands for screen to interpret. Keeping in mind that all keys are case-sensitive (as most things are in Linux), take a look at some of the commands below:

C-a c - Create a new screen window

C-a A - Rename the screen

C-a C-a - Go back to the previous window

C-a <0-9> - Switch to screen #0-9 (quick toggle)

C-a " - View a list of the current screens, which will allow you to select one from the list

C-a ' - Enter a screen number to switch to (slower version of C-a <0-9>)

C-a d - Detach the whole screen session and fork to the background. Very useful for remote sessions you want to leave open. The command "screen -r" will resume your screen session.

C-a <Escape> - Scroll up through your command line "history" and see what output you previously got. Hitting <Escape> again cancels it.

With the introduction of Byobu in Ubuntu 9.10, you can also get some statistics added to the bottom of your command line window to help keep you informed about the state of the system you are running on. Hitting F9 in session will bring up the menu for customization, which can make your screen session look pretty awesome. Instead of using screen to start your screen session, simply use byobu instead. Easy as pie.

If you have any questions about GNU Screen or Byobu, let me know and I’ll see what I can do to answer them. Stay tuned on Friday for another issue of “Five Things” (hopefully).

From Paperwork to Web 2.0: UMSwing’s New Membership System

Nowadays, my life has a good amount of its time consumed with either work or swing dancing. I work every weekday, and four nights every week I’m dancing. Being the nerd that I am, I always look for opportunities to intertwine my hobbies, despite them being complete opposites. Being on the executive committee helps a lot with that, since I take the position of Web Administrator and Graphics Designer with UMSwing.

On the way home from an event a couple weeks ago, I was talking with a friend about the hassle of all the paperwork we have to go through every time we have a lesson; we need to fill out transaction logs for each payment, keep track of every person’s attendance for each class, and also mark it on their membership form that they attended and paid for that class. A single person dropping in to that class requires writing on three sheets of paper. When you’re trying to run everybody through quickly, that starts becoming an issue.

This friend, being the kind of person that seems to regurgitate good ideas on demand, suggested to me, “Brian, you’re a developer. Just write a program to do it for you. You’re learning Ruby and Rails, so you can do a web-based backend and a GUI frontend. Problem solved!”. Thus, I sat down and started planning. Rails seems to be yet another one of those languages that lacks any decent documentation or tutorials. If you plan on learning it, pick up “Agile Web Development With Rails“. It is by far the best development book I have ever read. If it’s any sort of selling point, one of the authors created the Rails framework; if he doesn’t know how to use the framework, nobody does.

As a method for potentially helping me brainstorm, I’ve decided to spill out some of my ideas and goals here. I’m only going to discuss a few ideas here; while I would normally immediately distribute this idea into the public domain, I’ve decided to keep this one closed source. If you have any suggestions or ideas, let me know and I will give you credit. Better yet, if you’re interested in this software, get in touch and we can discuss it.

Goals for Dance Site

  • Members: Keep track of all members, regardless of how long ago they joined. Eliminate the need to fill out a new membership form every semester. Each member should be assigned a member number, which can be put on a barcode. Keep track of personal information, interests, and attendance. Gather statistics/metrics from attendance vs. month/day/semester, etc.
  • Memberships: Handle multiple membership types, including drop-in. Integrate with finances to determine when a user has paid for their membership through drop-ins. Support for online payments through Paypal (ie. Mastercard, Visa, eCheck, etc.)
  • Finances: handle per-lesson incomes. Support for multiple lessons per day. Keep track of what is taught during that lesson. Provide unlockable content for each lesson; attendance to that lesson unlocks the content for that member; refresher videos, class notes, etc. Support for discounted membership dates/times.
  • Graduated system: attendance of X number of events allows you to attend higher level classes. Ability to override by administrator.
  • Mailing List: Separate old members by current members, allowing for class updates to be sent to current members, while global events to be sent to all. Ability to unsubscribe.