Ben Scheirman

These fickle bits...

Menu

Rails Intrigue Video at NHDNUG

I gave a presentation at the North Houston .NET User Group a couple weeks ago entitled “Rails Intrigue”. My friend, Claudio Lassala recorded it and posted the video on YouTube.

In the presentation, I tried to give a little glimpse of what it feels like to build an application with Rails. I also tried to convey a little of why I think Rails is just Fun.

I think it went pretty well, for being mostly off the cuff. Give it a watch, and let me know what you think.

Houston Code Camp - Call for Speakers

I’m excited to announce the first annual Houston Code Camp 2011, happening on August 20th! The code camp is a one day conference on Saturday, held by developers - for developers. Here you’ll find sessions on a multitude of platforms and of varying skill levels. Best of all? It’s FREE.


logo.jpg

Call for speakers

We’re currently looking for speakers, so if you are interested in speaking please feel free to submit a session. We’re interested in both veteran & novice speakers alike, as a code camp is the perfect opportunity to start speaking if it’s something you’ve been wanting to do.

Community Voting of Sessions

We want this conference to be valuable to the community, so we’re letting you vote for the sessions you’d like to see most. As registration draws near I’ll announce more details on how this work.

Registration will open soon, but for now…. save the date!

Dry Up Your Rspec Files With Subject & Let Blocks

Rspec is pretty awesome, however due to its flexibility, often times I find that people write specs in ways that either a) aren’t structured very well, or b) use the wrong terminology to group up common contexts & behaviors.

Update: Be sure to read David Chelimsky’s suggestions in the comments.

A friend of mine who is fairly new to Rspec, and asked me to provide some feedback on some tests that he wrote.

Here is the before:

The only real problems here are:

  • Lots of duplicated setup code. If the initialization aspect of the Card design ever called for something other than a string, we’d have a lot of test code to fix.
  • Lots of “extra” code to test a simple value. If it smells like duplication to type “it ‘has a value of 13’” and then type the same thing, only in ruby code, then you’re right.

The rspec constructs I recommend to deal with this are `subject,` `let, and` `its` blocks.

  • Subject blocks allow you to control the initialization of the subject under test. If you don’t have any custom initialization required, then you’re given a default `subject` method already. All it does is call `new` on the class you’re testing.
  • Let blocks allow you to provide some input to the subject block that change in various contexts. This way you can simply provide an alternative `let` block for a given value and not have to duplicate the setup code for the subject over again. Let blocks also work inside of `before :each` blocks if you need them.
  • Its blocks allow you to test methods on the subject that return a simple value. The benefit of using this over the more wordy version above is that it can actually format the test output for you.

Here is the same example above, using the above techniques to clean things up a bit.

And here is the output of the above spec:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Card
  #value
    Two of Hearts
      value
        should == 2
    Face Cards
      King of Clubs
        value
          should == 13
      Queen of Clubs
        value
          should == 12
      Jack of Hearts
        value
          should == 11
    Bad Value
      should raise StandardError

I think that’s a big improvement.

Note: The code in this post is delivered via Github Gists, which unfortunately don’t render in Google Reader. Click through to see the code.

2011 Ultimate Tools List for Mac

In pure Hanselman-style, I present to you the 2011 Ultimate Tools List for Mac.

I posed a list of tools last year when I got my first MacBook Pro. Since then I’ve had plenty of time to find some new gems, retire some old ones, and decided that I should share my list with the world.

In each section, I’ll list why I like each app, whether or not it’s free or not, and occasionally list some honorable mentions that lost out to another app, however is worth mentioning anyway.

Without further ado…

The Big 10 Life Changing apps

These are the must-haves, and are among the first installed on any new machine.

  • Dropbox (free) - Painless file sync between computers. One of the most useful apps of all time. (if you’re going to sign up, consider using my referral link)
  • Alfred (free) - Awesome launcher utility. Sort of like Launchy & SlickRun for windows. (Event more awesome with Powerpack paid addon which gives you file operations, clipboard history, iTunes searching/playing and more). Special mention goes to QuickSilver and LaunchBar, both of which are fantastic.
  • 1Password ($40) - Stop using the same password for multiple sites. Keep all of your passwords and secure notes encrypted in one place. Easily access your passwords using browser plugins. Sync with Dropbox. Even use on your iPhone!
  • Evernote (free) - I use this to take client meeting notes, scan receipts & documents I need to keep, and anything else I think I’ll want to refer to later.
  • Sparrow ($10) - The best desktop Gmail I’ve used. I like it so much, I stopped using Gmail from the browser.
  • TextMate ($60) - The old standard. Still my favorite editor for Rails work. Hopefully TextMate 2 will ship before I’m 40.
  • PeepOpen ($12) - A better file CMD-T file opener for TextMate, MacVim, and Xcode. Does fuzzy searching on path & filename and is insanely fast.
  • Charles Proxy ($50, free for minor use) - An awesome web debugging proxy. Inspect HTTP traffic including request/response, HTTP Headers, format as JSON, XML, Image, files, etc. Even self-sign SSL certs to view HTTPS traffic.
  • rvm (free) - Leverage many versions of ruby and maintain separate gemsets for each rails application. A must have for any ruby developer.
  • Twitter for Mac (free) - Of all the Twitter clients, this is by far my favorite.

General System Apps

These are the generally helpful apps that didn’t go into any other category

  • SizeUp ($13) - Keyboard shortcuts to pin windows to the left side, right side, switch monitors or spaces, minimize, maximize.
  • Chicken of the VNC (free) - A VNC client is a must on any system
  • uTorrent (free) - For those Linux distros & stuff
  • Fluid (free) - Turn your favorite web apps into real mac apps.

Music

  • Rdio ($10/month) - The Mac client to the Rdio service is awesome. Listen to anything you want, even sync to your iPhone for offline listening.
  • Pandora (free) - The amazing internet radio that only plays music that you like. I pay for the Premium subscription to get access to the desktop app and to higher quality feeds.
  • Pandora Jam ($15) (scrobble Pandora with Last.fm, integrate with the keyboard controls & IM clients, and also record Pandora songs, if you so desire)
  • Tracks - Quick, keyboard access to your iTunes Library. I stopped using this once I bought the Alfred Powerpack, because it can do the same thing.

Productivity

Apps to make you faster, more organized, and get more things done. This is a favorite of mine.

  • Things ($50) - One of the most well designed applications on the Mac. Track things left to do in various projects, set due dates, etc. I have mine synching with Dropbox, which works just fine. An update with “true” sync is in the works and should work on iOS as well. Doesn’t do a few things I’d like, such as integrating with iCal for reminders and push notifications on the iPhone app, but all in all, one of the best Mac apps around.
  • The Hit List ($50) - I LOVE this app. I like it better than Things. Unfortunately, I started using it in 2009 and it’s still in Beta. Seriously. The last 20 or so updates have simply said “Extending the beta period”. Apparently they are hard at work at a 1.0 release to coincide with their iPhone app they’ve been working on since early 2010. But at this pace, I wonder if they’ll ever ship.
  • Wunderlist (free) - This app is really nice, however it lacks a lot of the smaller things you’d get from a full-fledged native app like Things or THL. That said, it’s a quick & easy way to share todo lists amongst many devices, the web, as well as share with other people. Recommended.
  • Pomodoro App (free) - If you’re into doing “tomatoes,” or time-boxed sprints of distraction-free, focused work, this app can help you manage it.
  • TimeSink ($5) - Shows you how much time you spend in each app. Answers the question, “How long did I spend reading Twitter today?”
  • MindNode (free/pro versions) - Simple Mind Mapping tool. They even have an iPad app. Great for getting loose ideas down & organizing into groupings.
  • TextExpander ($35) - Create snippets that expand into larger, commonly typed expressions. Useful in email for signatures, or even in code. I use them to easily expand the lengthy property syntax in Objective-C.

File Transfer / Sync / Backup

  • Transmit ($34) - Simply the best FTP app out there. Does SSH, SFTP, S3, and more. It’s fast and beautiful.
  • Cyberduck (free) - Decent FTP program for those who don’t want to shell out money for a tool they use maybe twice a year. Also supports S3 & other cloud drives.
  • S3Hub (free) - Easy, free, access to buckets, files, & permissions on S3.
  • Receivd (subscription) - Send & receive large files between groups of people. If you need to frequently share large files with peers, forget email, forget skype. Use received.
  • Carbonite / Mozy / Backblaze / Crashplan - All of these basically do the same thing: back up your files online in the background. I’ve used Carbonite & Mozy, and I have had minor issues with both. Ultimately I decided that it wasn’t worth the performance hit to do this. I may try this again in the future, and if I do, I’ll try out Back Blaze.
  • Carbon Copy Cloner (free) - Easily clone a drive & restore it later. Seriously easy to use, and completely free.

Editors

  • TextMate - as mentioned above.
  • MacVim - I really want to get better at vim, and occasionally I’ll spend the day in MacVim to keep my chops. I can definitely see some aspects of improvement, but ultimately I’m faster with TextMate.
  • vico (alpha) - An interesting marriage of TextMate beauty and VIM speed & efficiency. It’s early alpha, but definitely one to watch.
  • Espresso ($65) - HTML, CSS, PHP Editor, great for WordPress site maintenance. Sexy UI.
  • CSSEdit ($40) - Powerful CSS editing, live preview, and CSS organization built-in. These MacRabbit guys make a damn fine user interface.
  • TextWrangler (free) - A decent text editor with powerful editing capabilities. A “little brother” to the for-pay BBEdit.
  • Coda ($99) - If I were doing PHP websites full time, I’d probably use this. Crazy powerful, connect to remote sites with ease, lookup documentation, and access the context-sensitive terminal straight from within the app. Oh, and it also has Subethaedit functionality for shared editing in real-time. Epic!

Graphics & Photos

  • Acorn ($50) - An excellent, affordable image editor that can do many of the things a web/iOS developer needs. My current favorite. Still not Photoshop though.
  • Pixelmator ($60) - Another cheap alternative to Photoshop. Does a lot of things well. Similar to Acorn in functionality, though not as minimal in design.
  • OmniGraffle ($99) - Seriously powerful diagramming. Worlds better than Visio.
  • Balsamiq Mockups ($75) - Rapid sketch-wireframing tool. Great way to create mockups to validate a user interface.
  • Opacity ($40) - Great for making icons, buttons, logos, & other artwork. The interesting part: It can give you CoreGraphics code to replicate the same image in code. Also has factories for automatically generating regular size + 2X images for Retina graphics on iOS.
  • Photoshop ($billions) - Still my favorite graphics editor, though too expensive for me to justify a license.
  • Picturesque ($30) - Quickly add rounded corners, reflections, perspectives, & other effects to photos.

Communications

  • Skype (free) - An essential part of our workplace. We use it for chat, remote pairing, and small meetings. Unfortunately, Skype has taken a turn for the worse. I’ll looking for alternatives.
  • Gabble (free) - The only Yammer client that doesn’t suck balls. Adobe Air is a joke, this app brings a native Cocoa UI & is much more friendly to use.
  • Adium (free) - Multi-platform chat client. Not a complete replacement for iChat, though, because it doesn’t do voice & video.
  • Colloquy (free) - Excellent IRC program.
  • Facetime ($1) - Call iPhone 4’s & iPad 2’s. Or call other Macs with Facetime.
  • GotoMeeting (subscription) - We use GotoMeeting for lots of our meetings. Share your screen, invite lots of people, use the built-in VOIP service or allow your clients to dial into a real phone #. Also works on iPad!

Video

  • VLC (free) - Having trouble playing a video format? VLC plays damn near everything you throw at it.
  • Handbrake (free) - Rip DVDs and batch encode videos for playback on your iPad or iPhone. Seriously powerful. Who needs raw ffmpeg?
  • Flip4Mac (free) - Play WMV files on your Mac.
  • Rivet ($20) - Have a PS3 or Xbox360? Stream your movies from your Mac while transcoding weird video formats. This is an essential part of my home media experience.
  • AirVideo Server (free Mac client)- Similar to Rivet, but for your iOS devices.

Audio

  • WireTap Studio ($70) - Record audio from your computer. Even isolate by application! Need to snag some audio from a youtube video? Want to record a skype call? WireTap Studio has you covered.
  • Garage Band 11 (part of iLife) - I love this app. Powerful multi-track recording, software instruments, and powerful effects. I use this all the time to play electric guitar using nothing but the software amps & pedals. Combine with a cheap tube pre-amp and an M-Audio USB interface and you’re good to go!

Source Control

  • GitX (free) - Simple way to view your git log & all of your branches. Doesn’t make your eyes bleed like gitk. Make sure you enable the Terminal command use so you can type “gitx” from your git repo in Terminal.
  • Tower ($60) - If you need a gui for git, look no further.
  • Versions (€ 39.00) - If you’re stuck on Subversion still, this app is a must. Gorgeous UI.

File Diffs

  • Kaleidoscope (€ 29.00) - Wonderfully brilliant file & image comparison tool for Mac. Integrates with Git. Hoping they support merge soon.
  • p4Merge (free) - Decent 3-way merge tool for Git. Sucks the least out of all of the ones I’ve tried.

Office

  • Microsoft Office for Mac ($150) - I use this for Word & Excel. Shitty user interface, but seamless compatibility with their Windows counterparts.
  • iWork ($49) - Not a complete MS Office replacement (though it’s darn close). I mostly use this for Keynote & occasionally Pages. Keynote is amazing. 1200% better than PowerPoint.

Blogging

This is one of the sore spots on the Mac. Nothing really comes close to a Windows Live Writer experience on the Mac.

  • ecto ($20) - I’m writing this post in ecto. I like the custom toolbar for adding your own custom tags, but the UI is a little clunky and has some quirks that I don’t understand. So far the best I’ve found.
  • MarsEdit ($40) - I want to like this app, but I had issues with it. It emitted some pretty horrid HTML and I found it difficult to work with.
  • Blogo ($25) - Interesting newcomer, but I didn’t find it to fit into my blogging workflow.

Databases

  • Sequel Pro (free) - Manage MySQL databases like a pro. Sports a UI that doesn’t suck.
  • Base (£19) - The best app for managing SQLite databases. Sure SQLiteManager for Firefox is free, but it’s awkward to manage databases from Firefox and the UI is terrible. Base is worth the money.
  • pgAdmin (free) - Since postgres is my database of choice these days, I need a good GUI tool. Sadly, there are none. Utterly ugly, but pgAdmin gets the job done.
  • MongoHub (free) - A handful of our projects utilize MongoDB, and MongoHub is my preferred way of interacting with these databases. Also has a MapReduce tool!
  • Navicat Lite (free) - I don’t use this, but a few friends do. Works with many databases.
  • RazorSQL ($70) - Possible the ugliest application I have ever seen. But if you need 1 app for just about every SQL database on the planet, RazorSQL has you covered.

System

  • homebrew (free) - I don’t use MacPorts or Fink anymore. Easily install most OS packages via Homebrew.
  • FreeRuler (free) - for keeping pixels inline. Gives you a pixel screen ruler that is super handy.
  • Digital Color Meter (built-in) - Wanted to mention this one because it is already included on your Mac! Quickly snag a color from anything on your screen. Outputs color as Hex or % values for RGB.
  • Caffeine (free) - Prevent your Mac from going to sleep when you click on the icon. Super-effective, and such a simple idea. I use this at least once a week.
  • iStat Menus ($16) - Monitor your system resources from your menu bar. Better battery meter, bandwidth graphs, cpu/ram/hard disk meters, and more. Completely customizable.
  • Rubbernet (€30) - Detailed analysis of network activity broken down by application. Handy for telling how much bandwidth an app is taking up or for identifying applications that phone home.
  • Xbench (free) - Benchmark your Mac’s performance. I used this to take before/after hard drive scores when installing my SSD.

Email


Grab Bag

  • Delicious Library ($25) - A seriously cool library application for keeping track of your books, music, movies, & software. Integrates with the iSight camera for bar code reading. Definitely a must-have.
  • PhoneView ($25) - Read files from your iPhone without iTunes. Has additional features that work with Jailbroken iPhones.
  • iSale ($24) - Sell things on Ebay with style.
  • SousChef ($30) - Cool recipe management for Mac. Easily paste in recipes, identify the various sections, and it parses ingredients, instructions, and yield as well. Drag a picture from the web & drop it on the recipe to assign an image. Also has a mode with gigantic text that you can read from across the room (works with the remote!)
  • Cross Loop (free) - Remote tech-support with other Mac & Windows computers over the internet.
  • Celestia (free) - Take a trip to Neptune, visit other galaxies, and take a look at stars. Cool 3D program, great for kids.

Screencasting

  • Screenflow ($99) - Of all of the screencasting programs, I found this one to be the most joy to use. Easily record screen, iSight camera, and audio (both from system audio & mic). The editing features were easy to use and included some really cool effets.
  • iShowU Classic ($20) - Cheap and effective. Easily record a small section of the screen. This is what I used to record all of the episodes for the Tekpub iPhone Series.
  • Camtasia ($99) - I got a free license to this from my MVP. It is a good contender. I didn’t like it at first because it wasn’t possible to just record a small section of the screen. Apparently they’ve fixed it. If you’re familiar with Camtasia on Windows, you’ll probably feel right at home with Camtasia for Mac.
  • KeyCastr (free) - Of course during screencasting it is usually helpful to show what keystrokes you’re using. KeyCastr does that beautifully.

Screen Capture

Capturing your screen (or a portion of it) is built-in to the Mac, but occasionally you want to mark them up & share them quickly on the web.

  • LittleSnapper ($30) - A good way to quickly annotate pictures, keep a library of shots, and share them on the web.
  • Skitch (free) - Also good (feature-wise), but I dislike their non-standard UI immensely.

Virtualization

  • VMWare Fusion ($80) - Run your VMs with ease.
  • Parallels ($80) - My current Windows VMs are in Parallels (mostly because Parallels was faster and had better DirectX support, thus games worked better) but nowadays VMWare Fusion & Parallels are pretty much equivalent). I just happen to own both.
  • Virtual Box (free) - If you need free virtualization software, look no further.


General Development

  • MonoDevelop (free) - For when I want to write .NET code without opening a VM. Also used for MonoTouch & MonoDroid.
  • HTTP Client (free) - A fantastic HTTP workbench. Essential when dealing with HTTP APIs.
  • SOAP Client (free) - If you are unlucky enough to have to work with SOAP web services, this little app can help you.
  • Gitifier (free) - A nifty tool to notify you when people push code to your monitored git repositories.
  • HTTP Scoop ($15) - Recommended by Kevin Lee. A great HTTP traffic inspector.
  • Charles Proxy - As mentioned above.

iOS Development

  • AppViz ($30) - Analyze app store sales & reviews. I use this to keep track of my app income for tax purposes as well.
  • iOS Simulator Cropper (free) - Capture screenshots of the iPhone/iPad simulator for use on websites or the app store. A must-have.
  • iConify (free) - drag one 512px image & spits out every possible icon size needed for iOS development. Also handles the regular/retina resizing.
  • CodePilot ($30) - Adds some nice productivity enhancements to Xcode 3. Apparently they’re working on an Xcode 4 version.
  • MoGenerator and Xmo’d (free) - Automatically generate sensible classes from your Core Data model. with xmo’d, it generates it whenever the model changes.
  • App Resigner (free) - Stuck with an ad-hoc build of app that was signed without your device included? Resign it in a snap!
  • Sound Stage ($5) Quick & Easy way to make iPhone app trailers (hat tip to Kevin Lee for this one).

Phew! That’s a big list. I’m sure that I’ve left out some gems, so if there’s something blatantly obvious that I should have included in this list, please feel free to leave a comment.

Using Guard & Spork With Mongoid & Devise

On my last project, I eventually settled on using Guard along with Spork to allow for quicker testing. Specifically, I used:

  • rspec
  • spork
  • rb-fsevent
  • guard
  • guard-rspec
  • guard-pow
  • guard-spork

You might be saying, “What the hell are all these gems for?!?!”

Guard

This is a lot of development gem dependencies, but once working, it can vastly grease your testing workflow. Guard is a framework for watching files & doing something when they change. Make sure to use rb-fsevent as well to make detecting files not melt your machine polling for changes.

Guard-rspec

guard-rspec notices that models and/or specs change, and runs the related spec file automatically. Just running one test makes things faster, but you still have to reload all of rails with each run, making the feedback loop completely undesirable.

Spork

This is where Spork comes in. Spork pre-loads your environment, allowing rspec files to run with –drb mode & essentially caching your environment for multiple, fast test runs. That is, unless you change something in the environment (such as config/environment, routes.rb, or Gemile). These changes require spork to be restarted, which is SLOOOOW.

It’s not always obvious when spork needs reloading, so sometimes you’d find yourself scratching your head, saying, “this test should be failing… but it’s not!” Followed by a head-slap, when you realize you need to bounce spork.

Guard-spork

So guard-spork is a nice way of automatically detecting these changes and reloading spork for you.

Guard-pow

Lastly, I’m using pow from 37signals, so any env related changes that require a server restart automatically call touch tmp/restart.txt and pow restarts the app. Guard-pow does this for you.

Workflow

It’s hard to say what all this means for the developer’s workflow, but basically all you need to do is run `guard` in a Terminal tab of its own and let it run. I run `guard` almost all day, and it generally does what I need it to.

Life is good, until you try to use this on another project that uses Mongoid & Devise…

The Problem with Mongoid + Spork

Mongoid include its models with Rails, so that means if you change your models you have to reload rails. Not very friendly with a Spork-type model. Hopefully they’ll add a lifecycle hook in the future, but until they do, we can utilize a feature of Spork that can save the day: `trap_method/trap_class_method`.

The details are found here, but for the impatient, I modified my `spec_helper`’s prefork block to look like this:

1
2
3
4
5
6
7
8
Spork.prefork do<br />  ENV["RAILS_ENV"] ||= 'test'<br /><br />
  require 'rails/mongoid'
  Spork.trap_class_method(Rails::Mongoid, :load_models)

  # Now load our environment
  require File.expand_path("../../config/environment", __FILE__)
  require 'rspec/rails'
  ...

Basically this forces that call to be loaded later on in the lifecycle.

There’s a similar interception done for Device, which likes to load models along with Rails routes. You might also need to use this technique to deal with similar issues with Factory Girl, Machinist, and Shoulda Macros as well.

And now my specs are faster again. Yay!

Is the Complexity Worth it?

Is this complexity worth it? Some would say no, and I’m certainly aware of how much additional “gem weight” this adds to a project.

For a great discussion about how to make your specs fast without requiring the complexity of Spork, check out the latest episode of Destroy All Software: Fast Specs with and without Rails. These screencasts are excellent..

Private Categories in Objective-C

Sometimes properties can vastly simplify the memory management code when working with your private instance variables (or ivars). Here is an example:

MyTableViewController.h

1
2
3
4
5
6
7
8
9
@interface MyTableViewController : UITableViewController {
    NSArray *items;
}

@property (nonatomic, retain) NSArray *items;

- (void)somethingChanged;

@end

MyTableViewController.m

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@implementation MyTableViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    //using the ivar
    items = [[NSArray arrayWithObjects:@"Item 1", @"Item 2", nil] retain];
    //using the property
    self.items = [NSArray arrayWithObjects:@"Item 1", @"Item 2", nil];}

- (void)somethingChanged {
    //using the ivar
    [items release];
    items = [[NSArray arrayWithObjects:@"New Item 1", @"New Item 2", nil] retain];
    //using the property
    self.items = [NSArray arrayWithObjects:@"New Item 1", @"New Item 2", nil];
    [self.tableView reloadData];
}

- (void)dealloc {
    [items release];
    [super dealloc];
}@end

Notice that in each use of the ivar, we have to take special care to manage the memory properly. In the first case, we have to make sure to retain the value, because [NSArray arrayWithObjects:] returns an autoreleased instance. In the second case, we have to make sure and release the first array before assigning it to the second array.

The only questionable part of using properties is probably obvious: You have exposed your internal state to outside classes, but only for the benefit of your implentation. It seems odd to change your public API simply to make the implementation a bit cleaner. How can we fix this?

Categories

Before we solve the above problem, let’s take a slight detour and learn about categories. A category in Objective-C is similar to an extension method in .NET. You basically re-open the class, define a method (or many) and provide your implementation. The result is it appears as if those methods were part of the original class all along.

Here’s an example of putting a startsWith method on the string class:

NSString+FLUXAdditions.h

1
2
3
@interface NSString (FLUXAdditions)
- (BOOL)startsWith:(NSString *)prefix;
@end

NSString+FLUXAdditions.m

1
2
3
4
5
@implementation NSString (FLUXAdditions)
- (BOOL)startsWith:(NSString *)prefix {
return [[self substringToIndex:[prefix length]-1] isEqualTo:prefix];
}
@end

[box type=”info”]Notice the naming of the filename & the category name. Most people use the + syntax to denote a category on the class they’re adding on to. The prefix is also important. If you just name your category “Additions” then it’s possible that other libraries you include (or future versions of the SDK) could have the same name, leading to a collision. The common practice is to utilize a company prefix on classes that could be reused by others or that could cause collisions in the future.[/box] Now that I have that implemented, all I have to do is include my header file anywhere I want to use this method. You can even do this in a global header file.

1
#import "NSString+FLUXAdditions.h"
1
2
[@"My awesome string" startsWith:@"My"];  //returns YES
[@"My awesome string" startsWith:@"Foo"]; //returns NO;

So now that we understand how categories work, how can we utilize this to solve our original problem?

Private Categories

We can utilize private categories to give us the benefit of properties for our ivars, but at the same time, NOT expose those to the outside world. Here’s how it works (using our example from above):

MyTableViewController.m

1
2
3
@interface MyTableViewController ()
@property (nonatomic, retain) NSArray *items;
@end@implementation MyTableViewController@synthesize items;...@end

Notice how we declared the category interface directly the implementation file. This works because the .m file will only be loaded once, and since it’s inside the .m file, no other classes will ever know it existed. We can remove the property declaration from the header file and everything should work the same.

Private categories can also be used to provide method declarations, which can help you order your methods in a way that makes sense, and not worry about the compiler complaining about methods that haven’t been declared yet.

Private Category Gotcha

One thing that tripped me up is the name of the private category. When first doing this I originally chose the name “Private”. But there’s something peculiar about named category methods versus unnamed ones (like I have above).

Unfortunately Xcode4 wasn’t very smart about telling me what was wrong, instead giving me conflicting error messages:

This stack overflow answer helped explain the difference between the two styles.

Hopefully this helped you understand how to leverage categories to clean up your public APIs!

Increasing Shared Memory for Postgres on OS X

I came across a cryptic error while trying to create another database instance for my local Postgresql server. The error was:

1
2
3
4
5
6
7
creating template1 database in data/base/1 ...
FATAL: could not create shared memory segment: Cannot allocate memory
DETAIL: Failed system call was shmget(key=1, size=1318912, 03600).
HINT: This error usually means that PostgreSQL's request for a shared<br />memory segment exceeded available memory or swap space. To reduce the <br />request size (currently 1318912 bytes), reduce PostgreSQL's shared_buffers <br />parameter (currently 50) and/or its max_connections parameter (currently 10).
The PostgreSQL documentation contains more information about shared memory <br />configuration.
child process exited with exit code 1
initdb: removing contents of data directory "data"

The issue is that your Mac is not configured for “server” level resource usage. In order to check what your kernel settings are for shared memory, type:

1
sysctl -a

Look for keys that start with `kern.sysv.sh____`. Note that the numbers are somewhat related, so you have to change them together. Some helpful detail was found on this post:

Note that (kern.sysv.shmall * 4096) should be greater than or equal to kern.sysv.shmmax. kern.sysv.shmmax must also be a multiple of 4096.

You can set these values temporarily with `sysctl -w [keyname] [value]`, but to make them permanent, you can write the values to `/etc/sysctl.conf`. Here are the values I used:

1
2
3
4
5
6
7
kern.sysv.shmmax=1610612736
kern.sysv.shmall=393216
kern.sysv.shmmin=1
kern.sysv.shmmni=32
kern.sysv.shmseg=8
kern.maxprocperuid=512
kern.maxproc=2048

You’ll need to reboot, but once you’re back up you should be able to create more Postgres databases with ease.

Presentations From iPhone Dev Con Boston

I gave 2 talks at iPhone Dev Con in Boston. I’ve posted the slides & material online.

Effective iOS Network Programming Techniques

Objective-C & iPhone for .NET Developers

Demo code & slides for both sessions can be found on github.

Thanks to all who attended and left me such great reviews!

Book Review: Crafting Rails Applications

I just finished with Crafting Rails Applications by José Valim. The book claims to teach Expert Practices for Everyday Rails Development. I didn’t find it to be exactly that, however I did enjoy it and I learned a ton.

The Good

The book flows pretty well. Each chapter contains a challenge or set of related challenges and it’s pretty easy to follow along with the code. Each example contains automated tests, and he creates a gem for almost each solution, so that it is easy to see how to modularize things.
The coverage of Rails internals is really enlightening. Sometimes it can be a bit dry, but you’ll learn quite a few things about Renderers, Responders, Engines, Railties, Routing, Rack, Instruments, and more.
The book also contains a wide range of technology topics. José doesn’t just utilize Rails & ActiveRecord. Other examples include MongoMapper, Redis, and Sinatra.

The Bad

Even though each of the examples contains unit tests, they are written in a style that I find to be problematic in real systems. The concise nature of the tests is probably an artifact of being printed, but most of the testing examples utilize few test classes with many assertions per test method.
In addition, though he “writes” the tests before implementation, this actually hurts understandability in some cases. The reason is most of the tests read as if he already knew the implementation and knew exactly how to test it. But it isn’t apparent to the reader.
I tend to prefer RSpec with 1 assertion per test method and many fine-grained methods that test various behaviors in each context my system is in. The book’s Test::Unit style wasn’t something I’d suggest as a good way to test real applications.

The Bottom Line

Ultimately I think the book is excellent, and certainly gives plenty of information about Rails 3 internals. I think newcomers would probably be lost, but if you’re past the newbie stage with Rails then this book is recommended.

Mariachi Product Engineering

I spoke at iPhone Dev Con in Boston last week and I attended Mike Lee’s excellent keynote presentation: “Mariachi Product Engineering”

At iPhone Dev Con in San Diego last year, Mike came out dressed like a Pirate. No kidding.


mikelee-pirate

This year he came with a Mariachi outfit on. It’s pretty hilarious as nobody expects a keynote speaker to be dressed this way.

Over beers some of the guys at the conference decided it would be awesomely-epic to hire a real mariachi band to play during his keynote. So how does one find a mariachi band with after midnight on a Monday? Apparently, AMEX. One of the guys called his AMEX service and they delivered. I swear this could be the makings of a new AMEX commercial.

It made for a memorable keynote to say the least. The talk was excellent as well, as Mike certainly has a lot to say about Product Engineering.

Here is the video of the first 30 or so minutes of the talk (I ran out of battery before it was over).

Mike Lee - Mariachi Product Engineering from Ben Scheirman on Vimeo.

mikelee-mariachi.jpg

I’ll have links to my presentation material soon, but I wanted to share this awesome event. Certainly one for the books!