Posted over 2 years back at has_many :through - home
I was chatting with a friend over dinner this weekend about the impact of work environment on one's ability to excel as a software developer. We've both worked for companies where we've had to work far more than 40 hours each week for extended periods of time. We both agreed that's a good way to burn out your staff and, more importantly, a bad way to get stuff done faster. Sure, you can do an intense sprint now and then, but you don't win a marathon by running full out the whole way.
The comparison I came up with was that writing software is a lot like writing literature. It takes both discipline and creativity. Having either of those attributes will only get you so far (though it will probably put you ahead of most of the pack). To truly excel you must have both.
Discipline is not about putting in long hours (well sometimes it is, but that's not what I'm talking about). Discipline is about consistency. It's like playing blackjack and counting cards - your system won't pay off on every hand, but over time you will reap the rewards. Agile development is very much about that kind of discipline. You write your tests, go red, go green, refactor. This aspect of software is craftwork. It's methodical. It's not very exciting, but it gets you from point A to point B, and for the most part it's predictable.
Putting in 60+ hours a week is not good for your creative output. Being creative requires a brain that is rested and energized. It also takes mixing things up, changing perspective frequently. Burnout is the enemy! Sometimes when I'm stuck I'll get up and walk around the office, have a 5 minute chat with someone about something random. When I get back to my desk I can deal with the issue much better. Or if my pair and I get stuck, we'll put the story on hold for a little bit and tackle something tiny that lets us reset our perspective. That sort of thing usually helps a lot. We know enough not to try something really tough late in the day, and sometimes we save doing a fun story as a reward for finishing something that's no fun at all. Our brains naturally have attention spans that are too short to keep up with what we ask of them. Learn how to work with your brain instead of forcing it to do something it's not suited for.
There is a balance, and a way that discipline and working creatively mesh. Find a rhythm that works and that you can sustain, then stick with it. Back when I was trying to write science fiction, I got to talk to Cory Doctorow about his practice of writing. His advice was to write a page every day, then send it to people to get feedback. Pretty simple, eh? Cory produces a lot of fiction and I find it shocking that he only does a page a day. But a page a day lets him do a novel and a few short stories in a year, which is a lot more than I ever wrote when I was trying. I think he can probably keep that pace up forever. Sustainable pace wins.
One of the things I like best about working at Pivotal is that we consistently work at a sustainable pace. I can't believe how many startups advertise jobs where they say that they expect you to work "startup hours". I won't even consider working at a place like that ever again. It's not just because I don't like working that way myself, but because I think companies that expect and require that kind of pace from their developers are just going to screw themselves and burn out their developers. They'll either get real about what they can sustain, fail, or figure out how to deal with a high attrition/turnover rate.
Then there are companies that have no discipline and rely only on their "rock star" developers being able to come up with one inspired solution after another. Now, inspiration is great, but it doesn't get you even halfway there. People don't pay you for your ideas; they pay you for how you execute on them. If all you ever did was sit around and think up great solutions for difficult problems, you wouldn't ever get anything done. And if all you ever did was play Rock Band, you might be very inspired but you'd never finish writing Duke Nukem Forever.
As an ENTP (the personality type, not the company), working in a team is the only way I can consistently get things done over a long period. I can be super productive working with other people, but working on my own can be very challenging for more than a short time. It's much easier to keep up my discipline when I'm pairing since that helps me stay focused, and I can be very creative too, since I think better out loud. I know that way doesn't work for everyone, but it sure does for me. I also love tools like Pivotal Tracker that let me easily see what I have to work on next so I don't have to keep figuring it out every time I finish a task and need something else to do. On the other hand, I'm not a Calendar-About-Nothing kind of guy.
That's enough philosophy for the evening. But I'm curious to hear what other people feel about the interaction of discipline and creativity.
Posted over 2 years back at has_many :through - home
I was chatting with a friend over dinner this weekend about the impact of work environment on one's ability to excel as a software developer. We've both worked for companies where we've had to work far more than 40 hours each week for extended periods of time. We both agreed that's a good way to burn out your staff and, more importantly, a bad way to get stuff done faster. Sure, you can do an intense sprint now and then, but you don't win a marathon by running full out the whole way.
The comparison I came up with was that writing software is a lot like writing literature. It takes both discipline and creativity. Having either of those attributes will only get you so far (though it will probably put you ahead of most of the pack). To truly excel you must have both.
Discipline is not about putting in long hours (well sometimes it is, but that's not what I'm talking about). Discipline is about consistency. It's like playing blackjack and counting cards - your system won't pay off on every hand, but over time you will reap the rewards. Agile development is very much about that kind of discipline. You write your tests, go red, go green, refactor. This aspect of software is craftwork. It's methodical. It's not very exciting, but it gets you from point A to point B, and for the most part it's predictable.
Putting in 60+ hours a week is not good for your creative output. Being creative requires a brain that is rested and energized. It also takes mixing things up, changing perspective frequently. Burnout is the enemy! Sometimes when I'm stuck I'll get up and walk around the office, have a 5 minute chat with someone about something random. When I get back to my desk I can deal with the issue much better. Or if my pair and I get stuck, we'll put the story on hold for a little bit and tackle something tiny that lets us reset our perspective. That sort of thing usually helps a lot. We know enough not to try something really tough late in the day, and sometimes we save doing a fun story as a reward for finishing something that's no fun at all. Our brains naturally have attention spans that are too short to keep up with what we ask of them. Learn how to work with your brain instead of forcing it to do something it's not suited for.
There is a balance, and a way that discipline and working creatively mesh. Find a rhythm that works and that you can sustain, then stick with it. Back when I was trying to write science fiction, I got to talk to Cory Doctorow about his practice of writing. His advice was to write a page every day, then send it to people to get feedback. Pretty simple, eh? Cory produces a lot of fiction and I find it shocking that he only does a page a day. But a page a day lets him do a novel and a few short stories in a year, which is a lot more than I ever wrote when I was trying. I think he can probably keep that pace up forever. Sustainable pace wins.
One of the things I like best about working at Pivotal is that we consistently work at a sustainable pace. I can't believe how many startups advertise jobs where they say that they expect you to work "startup hours". I won't even consider working at a place like that ever again. It's not just because I don't like working that way myself, but because I think companies that expect and require that kind of pace from their developers are just going to screw themselves and burn out their developers. They'll either get real about what they can sustain, fail, or figure out how to deal with a high attrition/turnover rate.
Then there are companies that have no discipline and rely only on their "rock star" developers being able to come up with one inspired solution after another. Now, inspiration is great, but it doesn't get you even halfway there. People don't pay you for your ideas; they pay you for how you execute on them. If all you ever did was sit around and think up great solutions for difficult problems, you wouldn't ever get anything done. And if all you ever did was play Rock Band, you might be very inspired but you'd never finish writing Duke Nukem Forever.
As an ENTP (the personality type, not the company), working in a team is the only way I can consistently get things done over a long period. I can be super productive working with other people, but working on my own can be very challenging for more than a short time. It's much easier to keep up my discipline when I'm pairing since that helps me stay focused, and I can be very creative too, since I think better out loud. I know that way doesn't work for everyone, but it sure does for me. I also love tools like Pivotal Tracker that let me easily see what I have to work on next so I don't have to keep figuring it out every time I finish a task and need something else to do. On the other hand, I'm not a Calendar-About-Nothing kind of guy.
That's enough philosophy for the evening. But I'm curious to hear what other people feel about the interaction of discipline and creativity.
Posted over 2 years back at zerosum dirt(nap) - Home
Michael Bleigh’s TwitterAuth gem is truly full of awesome. It’s a complete OAuth authentication and API access solution for building Twitter apps with Rails. It uses familiar conventions borrowed from the Restful Authentication plugin, too. If you’re building a Rails-based app and you want to allow your users to Sign in with Twitter there’s just no better way to go.

For this particular app, I’m using the dynamic duo of Cucumber and Webrat to whip up integration tests. Since I initially stumbled a little bit when thinking about how to test integrated authentication against an external source like Twitter, I thought I’d doc the solution here in case other people were having the same issue.
Ready? Let’s do it.
Setup
First, install the TwitterAuth gem and use the provided generator to whip up the appropriate facilities. You’ll need to register your Twitter application accounts too. Or you know what? Screw it. If you want to make this super easy on yourself, Mike wrote a really great Twitter app Rails template that does all the setup for you, including walking you through getting the dev accounts. It’s nice, try it out. You’ll be up and writing Twitter apps in no time.
For the rest of this I’m going to assume that you have all of that working, and have installed Cucumber too. Don’t have Cucumber? Install it using RubyGems and then just run script/generate cucumber inside your Rails app.
Authentication Feature
So let’s write a Cucumber feature to test authentication in our boilerplate Twitter template application. Put the following in features/authentication.feature:
Feature: Authentication
In order to create and edit games
As a user
I want to sign in with Twitter
Scenario: Login via Twitter
When I go to "the homepage"
And I follow "Login via Twitter"
And Twitter authorizes me
Then I should see "Logged in as"
Scenario: Checking login status
Given I am signed in
When I go to "the homepage"
Then I should see "Logged in as"
Scenario: Log out
Given I am signed in
When I go to "the homepage"
And I follow "Log out"
Then I should see "Login via Twitter"
Step Definitions
Next, you’ll need to write step definitions to satisfy the missing steps. Do that by creating a file called features/step_definitions/auth_steps.rb. The content of the file should define the following two steps:
Given /^I am signed in$/ do
visit login_path
visit oauth_callback_path
end
When /^Twitter authorizes me$/ do
visit oauth_callback_path
end
Fake Style
The secret sauce here is FakeWeb. We’ll use it to fake out responses from the Twitter auth service so that your integration tests stay local (and reliable). Make sure to gem install fakeweb, and add the following to tests/environments/cucumber.rb:
config.gem "fakeweb", :version => ">= 1.2.5"
Now edit Cucumber’s features/support/env.rb file:
FakeWeb.allow_net_connect = false
FakeWeb.register_uri(:post, 'http://twitter.com/oauth/request_token', :body => 'oauth_token=fake&oauth_token_secret=fake')
FakeWeb.register_uri(:post, 'http://twitter.com/oauth/access_token', :body => 'oauth_token=fake&oauth_token_secret=fake')
FakeWeb.register_uri(:get, 'http://twitter.com/account/verify_credentials.json', :response => File.join(RAILS_ROOT, 'features', 'fixtures', 'verify_credentials.json'))
Here we’re stubbing out the interaction with Twitter auth, and responding to all outbound authorization attempts with canned data. Note that this references a fixture file, containing a sample verify_credentials API response from Twitter. You can obtain a copy using curl from the comfort of your terminal prompt (substitute your own username and password):
curl -i -u user:pass "http://twitter.com/account/verify_credentials.json" > verify_credentials.json
The last thing you’ll want to do is to check your twitter_auth.yml file and make sure there’s a cucumber environment defined in it. If not, you may need to add it.
And We’re Done
Alright that should do it. Go ahead and run rake features. Everything should be green. And green is good. If you need to write other features that are dependent on a login requirement, you can reuse the same “Given I am signed in” step that we created earlier.
Thanks to b.kocik, whose original post on using FakeWeb to stub Twitter auth was 80% of the solution I needed here.
Posted over 2 years back at Jake Scruggs
This summer I'm revisiting my short apprenticeship at Object Mentor. I'll be posting commentary on all my posts from the summer of 2004 exactly 5 years later to the day.
Monday 7-12-04
Today was a day of unintentional diversions. Paul and I came up with an idea of how to test an area of our state map compiler that had been eluding us. We would build up an input file, in the tests, and then send that input file into the SMC which would create an output file that we could read and check to make sure it works. If we had been designing this SMC thing from scratch using TDD, we could have made it easier to test, but since large parts of the program are a legacy, we had to resort to the building/writing/reading file method. But the parser in the SMC program doesn't like to be called twice, so a fair amount of the day was spent figuring out how to get around that for multiple tests. The other part of the day was spent writing a bunch of tests that had to be thrown out because there's a quirk of the program that given the same input, you may get different output. Everything will be there, but the order is not guaranteed. This is one of the problems with using a list, things may not come out in the order they were added. So our tests, which assumed a certain order, would randomly fail. Great. Luckily, there was only one test that really needed our new method of building/writing/reading so we could move all the old tests back to the old way (we called the program directly to set variables) and, in the one straggler, we re-wrote the test so that order was unimportant.
Pretty much the same thing was going on in the office. The email wasn't functioning and everybody who knew about the mail server was either out of town or teaching a class. Then Quickbooks started malfunctioning and things typed in by one person were not available to someone else in the system Nobody was sure if data might be getting lost -- this had the effect of chilling productivity in the office.
In short, everybody's 9am plans never even got started.
"If we had been designing this SMC thing from scratch using TDD, we could have made it easier to test..." How many times over the last five years have I run into this exact same problem? Too many to count -- lack of test leads to untestable code which is very often unmaintainable code.
Oh distant-past-jake, why didn't you just loop over the list you were trying to test and see if the things you wanted were in there? Ah well, a testing technique I would soon learn the hard way
.
Posted over 2 years back at ones zeros majors and minors
I just finished a rough 1.0 of my first MacRuby app: Bacondrop.
It’s a simple app for uploading files to Baconfile. Which, in turn, is a simple (and slick) interface to S3.
MacRuby is great.
Posted over 2 years back at Encytemedia - Home
If you’ve ever tried to do networking with Foundation you know that wrestling with NSURLConnection and NSURLRequest can be painful. Thankfully, we’ve seen a few third party tools step up to alleviate some of this pain. I want to introduce you to a couple of those tools and show you what I’ve been working on as well.

UPDATED: Fixed the permission issue on the download link
The current crop of tools
There are some excellent HTTP libraries available for the iPhone and OS X. So why do we need another one? Balance. There are two particularly popular libraries that I’m going to talk about: ASIHTTPRequest and ObjectiveResource. I’ll explain the benefits and tradeoffs of each and also explain where HTTPRiot fits in to this equation.
ASIHTTPRequest is a highly flexible lower level tool (relative to HTTPRiot & ObjectiveResource). It can do a lot of things and do them well. Besides the basic GET, POST, PUT and DELETE you can also upload files, post form encoded data, handle basic authentication and a host of other really nice things. Not to mention it can handle synchronous and asynchronous requests–something HTTPRiot and ObjectiveResource can’t do. This library is all about flexibility and this flexibility doesn’t take away from how easy it is to use. This code should definitely have in your bag of tricks when you’re looking for an all purpose HTTP library.
The tradeoff for ASIHTTPRequest is that it can’t automatically convert XML and JSON. There is also no mechanism for setting default configuration options which results in you having to configure things like delegates and selectors for every asynchronous request. To be fair, ASIHTTPRequest was never meant to be used this way, thus I would take these tradeoffs with a grain of salt.
If you’ve ever used ActiveResource with Rails you’ll probably be familiar with ObjectiveResource’s style. ObjectiveResources is a high-level library that does a lot of behind the scenes work. It’s built specifically to consume REST resources. It can convert to and from JSON and XML (ASIHTTPRequest can’t) and it will automatically initialize models and do all sorts of other work for you. This makes it a great fit for working in conjunction with a Rails app.
The tradeoff of ObjectiveResource is that it doesn’t handle XML and JSON that’s not produced by Rails well. I’m not sure what kind of results you’d get if you fed it something like Govtrack’s bill data. ObjectiveResource is also a big library with a lot of moving parts. In addition to the networking code, the library also includes ObjectiveSupport, a nice library in itself that’s loosely based on ActiveSupport.
One final thought about ObjectiveResource—there are a lot of methods added to NSObject. Apple doesn’t explicitly say not to do this, but they do warn you of the consequences:
“You can define categories that add methods to the root class, NSObject. Such methods are available to all instances and class objects that are linked into your code. Informal protocols—the basis for the Cocoa delegation mechanism—are declared as categories on NSObject. This wide exposure, however, has its dangers as well as its uses. The behavior you add to every object through a category on NSObject could have consequences that you might not be able to anticipate, leading to crashes, data corruption, or worse.”
With all that being said, ObjectiveResource is definitely worth checking out. I know a few people who are using it and love it.
Like ObjectiveResource, HTTPRiot was inspired by its Ruby counterpart: John Nunemaker’s httparty. Hence the name. HTTPRiot serves as a balance between ASIHTTPRequest and ObjectiveResource. You get a certain amount of flexibility and a higher level api. Like ASIHTTPRequest, you can send GET, POST, PUT, and DELETE requests, also like ObjectiveResource the XML or JSON response will automatically be converted to an Objective-C type (NSArray or NSDictionary).
The tradeoff with HTTPRiot is that it makes no attempt to convert the data further or automatically compose instances of other objects for you. It gives you the data and lets you do what you want with it. This means that you must be aware of the data you receive because it’s up to you to decide what to do with it after it’s been converted to a native type. For instance, if two request originate from the same model they will both use the same delegate methods to handle the response. It’s up to you to decide what’s what.
Some examples
Some quick examples to give you an idea of how you use HTTPRiot.
GET Request: Reads JSON from the server.
[Person getPath:@"/people" withOptions:nil object:nil];
POST Request: POSTs the body set in options to the server.
NSDictionary *options = [NSDictionary dictionaryWithObject:[foo JSONRepresentation] forKey:@"body"];
[HTTPRiotRestModel postPath:@"/person" withOptions:options error:nil];
Setting default options: You can subclass HRRestModel and set default options like basic auth, headers, params, etc. Every request you make from MyModel will use these default options.
@implementation MyModel
+(void) initialize {
[self setBasicAuthWithUsername:@"justin" password:@"pass"];
[self setDefaultHeaders:[NSDictionary dictionaryWithObject:@"Some Header Value" forKey:@"My-Header"]];
}
@end
Implementing the delegate methods
You’ll need to implement a few delegate methods to deal with the responses. I’ll explain why I settled on this approach in another post, but for now here is sample of what you’ll have:
- (void)restConnection:(NSURLConnection *)connection didReturnResource:(id)resource object:(id)object {
//resource contains the NSDictionary or NSArray version of the XML or JSON you requested
for(id item in resource) {
//Do something with your data
}
}
- (void)restConnection:(NSURLConnection *)connection didReceiveError:(NSError *)error response:(NSHTTPURLResponse *)response object:(id)object {
//Recieved a bad status code 404, 500, etc.
}
Summing up
All three libraries have a job they are well suited for. Hopefully I’ve given you an idea of what to expect with each one. On a final note regarding HTTPRiot, it is a young library so there will <strike>likely</strike> be bugs along the way. If you spot one, cease development and report it to the proper authorities.
Posted over 2 years back at A Fresh Cup
A few people have asked me about the Rails application template that I’ve put together recently. For those who are interested, it’s now available for review and download as a gist. To use it, just specify the -m switch when creating a Rails application:
rails new_app_name -m lark_template.rb
I should warn you of two things. First, it’s a pretty heavyweight template, sticking a lot of stuff into the new application. This suits me, because I have a lot of things I use in just about every application, but it may not suit you. Second, Rails templates are not one-size-fits-all; you’d be better off treating this as a starting point to steal from than a finished template to use (though if you want to use it, feel free).
Here’s a list of what this template sets up:
Coding Tools
- Authlogic for user authentication, including password resets, anonymous_only, authenticated_only, admin_only application helpers
- World’s simplest authorization system: manage multiple string roles on users with User#add_role, User#remove_role, User#clear_roles, and User#has_role?
- Date formats: :us, :us_with_time, :short_day, :long_day
- live-validations for client-side JavaScript data entry validation. Add :live_validations => true to form_for declarations to hook this up.
- Paperclip for attachment management
- /pages/css_test will show most CSS styles in action
- Searchlogic for magic named scopes and search forms – http://rdoc.info/projects/binarylogic/searchlogic. Includes attribute_equals, attribute_does_not_equal, attribute_begins_with, attribute_like, attribute_ends_with, attribute_greater_than, attribute_null, attribute_blank etc. etc.
- Stringex for extra string functionality – acts_as_url, String#to_ascii, String#to_html, String#to_url, String#remove_formatting, String.random
- US State application helpers
- will-paginate for pagination
Database Tools
- Hooked up for PostgreSQL
- admin-data plugin for administrative UI. http://localhost:3000/admin_data will get you to the application’s data. On production, only admin can view data, no one can edit (modify config/initializers/admin_data.rb to adjust this)
- db-populate for seed data
Deployment Tools
- fast_remote_cache strategy for deployment
- rubiadhstrano for deployment recipes; automatically uses multiple targets, so: cap production deploy for deployment to production
- superdeploy for additional Capistrano tasks. cap -T for full list.
External Services
- Exceptional for error tracking. Go to /pages/kaboom to test after finishing Exceptional setup.
- New Relic for performance tracking
Testing Tools
- Shoulda and Test::Unit for testing
- Mocha for mocking
- Object Daddy for factories
- Generated code is already covered by tests
- parallel-test for faster testing. rake test:parallel:prepare[2] to set up two test databases. rake test:parallel[2] to distribute tests across two cores
- rack-bug for request/response/perf analysis. http://localhost:3000/__rack_bug__/bookmarklet.html to add bookmarklet to browser.
- shmacros for additional Shoulda macros: should_accept_nested_attributes_for, should_act_as_taggable_on, should_callback, should_delegate, more
- More extra shoulda macros: should_have_before_filter, should_have_after_filter
- metric-fu for static code analysis. rake metrics:all, configure in Rakefile
- inaction-mailer is installed for development environment, so mails sent during dev will end up as files in /tmp/sent_mails
Posted over 2 years back at Dr Nic
The FutureRuby conference has been (and still is, as of 11:43am on Sunday) wonderful. I just finished my talk on “Living With 1000 Open Source Projects” which was great fun, good for a bunch of laughs, and more importantly allowed me to share some thoughts on Zero Maintenance, Managing community expectations, self-sustaining communities, and the difficulty of scaling pet children.
Below are the slides and all the nice things people said about the talk, which has made me feel very good for sharing, and for the 60hr return flight from Brisbane to Toronto.
If you want to hear the jokes, and an Australian “mistaking” Canada for a state of America, perhaps wait for InfoQ to publish the video.
The slides
Living With 1000 Open Source Projects<object style="margin:0px" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=livingwith1000opensourceprojects-novideos-090712054221-phpapp01&stripped_title=living-with-1000-open-source-projects"/><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=livingwith1000opensourceprojects-novideos-090712054221-phpapp01&stripped_title=living-with-1000-open-source-projects" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="355"></embed></object>
Nice things people said

Thanks to…
Elle Meredith who helped me design and theme the slides so they looked spot-on-awesome.
My two children for not being old enough to be disturbed by some of the things I said about them during the talk.
Posted over 2 years back at Katz Got Your Tongue?
This past week, I had a pretty long discussion on StackOverflow about Ruby and Python, that was touched off by question about whether there was anything special about Ruby that made it more amenable for Rails.
My initial response covered blocks (as a self-hosting way to improve the language) and the ability to define new “class keywords” because of the fact that class bodies are just normal executable code. The strongest argument against this was that Python decorators are as powerful as Ruby’s executable class bodies, and therefore can be used to achieve anything that Ruby can achieve.
Python decorators do in fact provide a certain amount of additional power and elegance over the Python before decorators. However, this power is simply a subset of the available Ruby functionality. This is because Ruby has always had the ability to add features like decorators to the language without needing language changes.
In other words, while Python has added a new hardcoded feature in order to achieve some of the power of Ruby, adding such a feature to Ruby would be unnecessary because of the underlying structure of the Ruby language.
To show this clearly, I have implemented a port of Python function decorators in under 70 lines of Ruby. I wrote the code test-first, porting the necessary functionality from two Python Decorator tutorials written by Bruce Eckel in October 2008.
The list of features supported:
- Decorate any object that responds to call via:
decorate SomeKlass or decorate some_lambda
- A simpler syntax for class names that can be used as decorators:
SomeKlass(arg)
- The ability to give the decorator a name that could be used instead of the class name, if desired
Some examples:
class MyDecorator
def initialize(klass, method)
@method = method
end
def call(this, *args)
puts "Before MyDecorator with #{args.inspect}"
@method.bind(this).call(*args)
puts "After MyDecorator with #{args.inspect}"
end
end
class WithDecorator
# we could trivially add these to all classes, but we'll keep it isolated
extend MethodDecorators
MyDecorator() # equivalent to decorate MyDecorator
def my_function(*args)
puts "Inside my_function with #{args.inspect}"
end
end
WithDecorator.new.my_function(1)
When MyDecorator() is called inside the WithDecorator class, it registers a decorator for the next method that is defined. This is roughly equivalent to Python’s function decoration. Some other examples:
class MyDecorator < Decorator
decorator_name :surround
def initialize(klass, method, *args)
@method, @args = method, args
end
def call(this, *args)
puts "Before MyDecorator(#{@args.inspect}) with #{args.inspect}"
@method.bind(this).call(*args)
puts "After MyDecorator(#{@args.inspect}) with #{args.inspect}"
end
end
class Class
include MethodDecorators
end
class WithDecorator
surround(1, 2)
def function(*args)
p args
end
end
WithDecorator.new.function(1)
In this case, I’ve inherited from the Decorator class, which allows me to add a decorator name, which can then be used in a class with MethodDecorators mixed in. In this example, I’ve mixed MethodDecorators into Class, which makes decorators available for all classes. Again, I could have made this the default, but I like to try to make new behaviors global if I can avoid it.
This is of course a first pass and I’m sure there are subtle inconsistencies between Python’s decorator implementation and what I have here. My point is just that the feature that was added to Python to add flexibility is merely a subset of the functionality available to Ruby, because Rubyists can implement new declarative features without needing help from the language implementors, and have always been able to.
<script type="text/javascript">
addthis_url = 'http%3A%2F%2Fyehudakatz.com%2F2009%2F07%2F11%2Fpython-decorators-in-ruby%2F';
addthis_title = 'Python+Decorators+in+Ruby';
addthis_pub = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12"></script>
Posted over 2 years back at Katz Got Your Tongue?
This past week, I had a pretty long discussion on StackOverflow about Ruby and Python, that was touched off by question about whether there was anything special about Ruby that made it more amenable for Rails.
My initial response covered blocks (as a self-hosting way to improve the language) and the ability to define new “class keywords” because of the fact that class bodies are just normal executable code. The strongest argument against this was that Python decorators are as powerful as Ruby’s executable class bodies, and therefore can be used to achieve anything that Ruby can achieve.
Python decorators do in fact provide a certain amount of additional power and elegance over the Python before decorators. However, this power is simply a subset of the available Ruby functionality. This is because Ruby has always had the ability to add features like decorators to the language without needing language changes.
In other words, while Python has added a new hardcoded feature in order to achieve some of the power of Ruby, adding such a feature to Ruby would be unnecessary because of the underlying structure of the Ruby language.
To show this clearly, I have implemented a port of Python function decorators in under 70 lines of Ruby. I wrote the code test-first, porting the necessary functionality from two Python Decorator tutorials written by Bruce Eckel in October 2008.
The list of features supported:
- Decorate any object that responds to call via:
decorate SomeKlass or decorate some_lambda
- A simpler syntax for class names that can be used as decorators:
SomeKlass(arg)
- The ability to give the decorator a name that could be used instead of the class name, if desired
Some examples:
class MyDecorator
def initialize(klass, method)
@method = method
end
def call(this, *args)
puts "Before MyDecorator with #{args.inspect}"
@method.bind(this).call(*args)
puts "After MyDecorator with #{args.inspect}"
end
end
class WithDecorator
# we could trivially add these to all classes, but we'll keep it isolated
extend MethodDecorators
MyDecorator() # equivalent to decorate MyDecorator
def my_function(*args)
puts "Inside my_function with #{args.inspect}"
end
end
WithDecorator.new.my_function(1)
When MyDecorator() is called inside the WithDecorator class, it registers a decorator for the next method that is defined. This is roughly equivalent to Python’s function decoration. Some other examples:
class MyDecorator < Decorator
decorator_name :surround
def initialize(klass, method, *args)
@method, @args = method, args
end
def call(this, *args)
puts "Before MyDecorator(#{@args.inspect}) with #{args.inspect}"
@method.bind(this).call(*args)
puts "After MyDecorator(#{@args.inspect}) with #{args.inspect}"
end
end
class Class
include MethodDecorators
end
class WithDecorator
surround(1, 2)
def function(*args)
p args
end
end
WithDecorator.new.function(1)
In this case, I’ve inherited from the Decorator class, which allows me to add a decorator name, which can then be used in a class with MethodDecorators mixed in. In this example, I’ve mixed MethodDecorators into Class, which makes decorators available for all classes. Again, I could have made this the default, but I like to try to make new behaviors global if I can avoid it.
This is of course a first pass and I’m sure there are subtle inconsistencies between Python’s decorator implementation and what I have here. My point is just that the feature that was added to Python to add flexibility is merely a subset of the functionality available to Ruby, because Rubyists can implement new declarative features without needing help from the language implementors, and have always been able to.
<script type="text/javascript">
addthis_url = 'http%3A%2F%2Fyehudakatz.com%2F2009%2F07%2F11%2Fpython-decorators-in-ruby%2F';
addthis_title = 'Python+Decorators+in+Ruby';
addthis_pub = '';
</script><script type="text/javascript" src="http://s7.addthis.com/js/addthis_widget.php?v=12"></script>
Posted over 2 years back at Encytemedia - Home
If you’ve ever tried to do networking with Foundation you know that wrestling with NSURLConnection and NSURLRequest can be painful. Thankfully, we’ve seen a few third party tools step up to alleviate some of this pain. I want to introduce you to a couple of those tools and show you what I’ve been working on as well.

UPDATED: Fixed the permission issue on the download link
The current crop of tools
There are some excellent HTTP libraries available for the iPhone and OS X. So why do we need another one? Balance. There are two particularly popular libraries that I’m going to talk about: ASIHTTPRequest and ObjectiveResource. I’ll explain the benefits and tradeoffs of each and also explain where HTTPRiot fits in to this equation.
ASIHTTPRequest is a highly flexible lower level tool (relative to HTTPRiot & ObjectiveResource). It can do a lot of things and do them well. Besides the basic GET, POST, PUT and DELETE you can also upload files, post form encoded data, handle basic authentication and a host of other really nice things. Not to mention it can handle synchronous and asynchronous requests–something HTTPRiot and ObjectiveResource can’t do. This library is all about flexibility and this flexibility doesn’t take away from how easy it is to use. This code should definitely have in your bag of tricks when you’re looking for an all purpose HTTP library.
The tradeoff for ASIHTTPRequest is that it can’t automatically convert XML and JSON. There is also no mechanism for setting default configuration options which results in you having to configure things like delegates and selectors for every asynchronous request. To be fair, ASIHTTPRequest was never meant to be used this way, thus I would take these tradeoffs with a grain of salt.
If you’ve ever used ActiveResource with Rails you’ll probably be familiar with ObjectiveResource’s style. ObjectiveResources is a high-level library that does a lot of behind the scenes work. It’s built specifically to consume REST resources. It can convert to and from JSON and XML (ASIHTTPRequest can’t) and it will automatically initialize models and do all sorts of other work for you. This makes it a great fit for working in conjunction with a Rails app.
The tradeoff of ObjectiveResource is that it doesn’t handle XML and JSON that’s not produced by Rails well. I’m not sure what kind of results you’d get if you fed it something like Govtrack’s bill data. ObjectiveResource is also a big library with a lot of moving parts. In addition to the networking code, the library also includes ObjectiveSupport, a nice library in itself that’s loosely based on ActiveSupport.
One final thought about ObjectiveResource—there are a lot of methods added to NSObject. Apple doesn’t explicitly say not to do this, but they do warn you of the consequences:
“You can define categories that add methods to the root class, NSObject. Such methods are available to all instances and class objects that are linked into your code. Informal protocols—the basis for the Cocoa delegation mechanism—are declared as categories on NSObject. This wide exposure, however, has its dangers as well as its uses. The behavior you add to every object through a category on NSObject could have consequences that you might not be able to anticipate, leading to crashes, data corruption, or worse.”
With all that being said, ObjectiveResource is definitely worth checking out. I know a few people who are using it and love it.
Like ObjectiveResource, HTTPRiot was inspired by its Ruby counterpart: John Nunemaker’s httparty. Hence the name. HTTPRiot serves as a balance between ASIHTTPRequest and ObjectiveResource. You get a certain amount of flexibility and a higher level api. Like ASIHTTPRequest, you can send GET, POST, PUT, and DELETE requests, also like ObjectiveResource the XML or JSON response will automatically be converted to an Objective-C type (NSArray or NSDictionary).
The tradeoff with HTTPRiot is that it makes no attempt to convert the data further or automatically compose instances of other objects for you. It gives you the data and lets you do what you want with it. This means that you must be aware of the data you receive because it’s up to you to decide what to do with it after it’s been converted to a native type. For instance, if two request originate from the same model they will both use the same delegate methods to handle the response. It’s up to you to decide what’s what.
Some examples
Some quick examples to give you an idea of how you use HTTPRiot.
GET Request: Reads JSON from the server.
[Person getPath:@"/people" withOptions:nil object:nil];
POST Request: POSTs the body set in options to the server.
NSDictionary *options = [NSDictionary dictionaryWithObject:[foo JSONRepresentation] forKey:@"body"];
[HTTPRiotRestModel postPath:@"/person" withOptions:options error:nil];
Setting default options: You can subclass HRRestModel and set default options like basic auth, headers, params, etc. Every request you make from MyModel will use these default options.
@implementation MyModel
+(void) initialize {
[self setBasicAuthWithUsername:@"justin" password:@"pass"];
[self setDefaultHeaders:[NSDictionary dictionaryWithObject:@"Some Header Value" forKey:@"My-Header"]];
}
@end
Implementing the delegate methods
You’ll need to implement a few delegate methods to deal with the responses. I’ll explain why I settled on this approach in another post, but for now here is sample of what you’ll have:
- (void)restConnection:(NSURLConnection *)connection didReturnResource:(id)resource object:(id)object {
//resource contains the NSDictionary or NSArray version of the XML or JSON you requested
for(id item in resource) {
//Do something with your data
}
}
- (void)restConnection:(NSURLConnection *)connection didReceiveError:(NSError *)error response:(NSHTTPURLResponse *)response object:(id)object {
//Recieved a bad status code 404, 500, etc.
}
Summing up
All three libraries have a job they are well suited for. Hopefully I’ve given you an idea of what to expect with each one. On a final note regarding HTTPRiot, it is a young library so there will <strike>likely</strike> be bugs along the way. If you spot one, cease development and report it to the proper authorities.
Posted over 2 years back at mir.aculo.us - Home
I’m proud to be a judge at the first ONYA awards, which celebrate all things web in New Zealand. Having been twice at Webstock, the awesomest web conference ever, I’m really honoured by this and are looking forward for your entries!
So, if you’re in New Zealand and have a really cool website, web application [...]
Posted over 2 years back at Encytemedia - Home
If you’ve ever tried to do networking with Foundation you know that wrestling with NSURLConnection and NSURLRequest can be painful. Thankfully, we’ve seen a few third party tools step up to alleviate some of this pain. I want to introduce you to a couple of those tools and show you what I’ve been working on as well.
UPDATED: Fixed the permission issue on the download link
There are some excellent HTTP libraries available for the iPhone and OS X. So why do we need another one? Balance. There are two particularly popular libraries that I’m going to talk about: ASIHTTPRequest and ObjectiveResource. I’ll explain the benefits and tradeoffs of each and also explain where HTTPRiot fits in to this equation.
ASIHTTPRequest is a highly flexible lower level tool (relative to HTTPRiot & ObjectiveResource). It can do a lot of things and do them well. Besides the basic GET, POST, PUT and DELETE you can also upload files, post form encoded data, handle basic authentication and a host of other really nice things. Not to mention it can handle synchronous and asynchronous requests–something HTTPRiot and ObjectiveResource can’t do. This library is all about flexibility and this flexibility doesn’t take away from how easy it is to use. This is code you should definitely have in your bag of tricks when you’re in need of an all purpose HTTP library.
The tradeoff for ASIHTTPRequest is that it can’t automatically convert XML and JSON. There is also no mechanism for setting default configuration options which results in you having to configure things like delegates and selectors for every asynchronous request. To be fair, ASIHTTPRequest was never meant to be used this way, thus I would take these tradeoffs with a grain of salt.
If you’ve ever used ActiveResource with Rails you’ll probably be familiar with ObjectiveResource’s style. ObjectiveResources is a high-level library that does a lot of behind the scenes work. It’s built specifically to consume REST resources. It can convert to and from JSON and XML (ASIHTTPRequest can’t) and it will automatically initialize models and do all sorts of other work for you. This makes it a great fit for working in conjunction with a Rails app.
The tradeoff of ObjectiveResource is that it doesn’t handle XML and JSON that’s not produced by Rails well. I’m not sure what kind of results you’d get if you fed it something like Govtrack’s bill data. ObjectiveResource is also a big library with a lot of moving parts. In addition to the networking code, the library also includes ObjectiveSupport, a nice library in itself that’s loosely based on ActiveSupport.
One final thought about ObjectiveResource—there are a lot of methods added to NSObject. Apple doesn’t explicitly say not to do this, but they do warn you of the consequences:
“You can define categories that add methods to the root class, NSObject. Such methods are available to all instances and class objects that are linked into your code. Informal protocols—the basis for the Cocoa delegation mechanism—are declared as categories on NSObject. This wide exposure, however, has its dangers as well as its uses. The behavior you add to every object through a category on NSObject could have consequences that you might not be able to anticipate, leading to crashes, data corruption, or worse.”
With all that being said, ObjectiveResource is definitely worth checking out. I know a few people who are using it and love it.
Like ObjectiveResource, HTTPRiot was inspired by its Ruby counterpart: John Nunemaker’s httparty. Hence the name. HTTPRiot serves as a balance between ASIHTTPRequest and ObjectiveResource. You get a certain amount of flexibility and a higher level api. Like ASIHTTPRequest, you can send GET, POST, PUT, and DELETE requests, also like ObjectiveResource the XML or JSON response will automatically be converted to an Objective-C type (NSArray or NSDictionary).
The tradeoff with HTTPRiot is that it makes no attempt to convert the data further or automatically compose instances of other objects for you. It gives you the data and lets you do what you want with it. This means that you must be aware of the data you receive because it’s up to you to decide what to do with it after it’s been converted to a native type. For instance, if two request originate from the same model they will both use the same delegate methods to handle the response. It’s up to you to decide what’s what.
Some examples
Some quick examples to give you an idea of how you use HTTPRiot.
GET Request: Reads JSON from the server.
[Person getPath:@"/people" withOptions:nil object:nil];
POST Request: POSTs the body set in options to the server.
NSDictionary *options = [NSDictionary dictionaryWithObject:[foo JSONRepresentation] forKey:@"body"];
[HTTPRiotRestModel postPath:@"/person" withOptions:options error:nil];
Setting default options: You can subclass HRRestModel and set default options like basic auth, headers, params, etc. Every request you make from MyModel will use these default options.
@implementation MyModel
+(void) initialize {
[self setBasicAuthWithUsername:@"justin" password:@"pass"];
[self setDefaultHeaders:[NSDictionary dictionaryWithObject:@"Some Header Value" forKey:@"My-Header"]];
}
@end
Implementing the delegate methods
You’ll need to implement a few delegate methods to deal with the responses. I’ll explain why I settled on this approach in another post, but for now here is sample of what you’ll have:
- (void)restConnection:(NSURLConnection *)connection didReturnResource:(id)resource object:(id)object {
//resource contains the NSDictionary or NSArray version of the XML or JSON you requested
for(id item in resource) {
//Do something with your data
}
}
- (void)restConnection:(NSURLConnection *)connection didReceiveError:(NSError *)error response:(NSHTTPURLResponse *)response object:(id)object {
//Recieved a bad status code 404, 500, etc.
}
Summing up
All three libraries have a job they are well suited for. Hopefully I’ve given you an idea of what to expect with each one. On a final note regarding HTTPRiot, it is a young library so there will likely be bugs along the way. If you spot one, cease development and report it to the proper authorities.

Posted over 2 years back at Segment7
Robot Co-op REST web services base class. This library makes it easy to
implement REST-like web services APIs.
Changes
- Upgrade to Nokogiri from REXML. This is incompatible with 2.x and older. Thanks Aaron Patterson!
Posted over 2 years back at GIANT ROBOTS SMASHING INTO OTHER GIANT ROBOTS - Home

Introduction
Creating buttons is something every web designer deals with, usually on a very regular basis. It can be one of those tasks that becomes tedious and repetitive but with a few tricks you can make pleasing looking buttons that also give the visitor useful feedback and navigational consistency. In this article I’ll be talking about buttons with 3 states – normal, hover, and pressed – and I will be using the sprite based method which places all 3 states in the same image file.
Shapes ‘n Shapes
Achieving the right graphical look is important so that you are able to present your design in the manner you desire – be it rational UI or crazy mystery meat navigation. It’s important to have your choices look deliberate and not haphazardly chosen – it will help you when presenting to the client and in the final UI users will interact with.
Photoshop’s shape tool is a quirky thing with a couple important options to understand before you start working. First there is the choice between creating a vector-based “Shape Layer” or a pixel based “Fill pixels” option. In a nutshell the vector option is versatile but clunky and the pixel option is less flexible (especially when you want to modify the shape later) but it acts predictably in the pixel world. I use pixels simply because the vector tool can be a pain.
Of equal importance is the “snap to pixels” option which is accessible from the hidden menu at the end of the shape option bar (see fig. 2, step 1) when you are using the rounded corner shape. This will prevent your shapes from displaying unpredictable antialiasing which becomes very important as you duplicate shapes and specify heights and widths in CSS. Also make certain if you’re created a rounded corner shape to turn anti-aliaising on (fig. 2, step 3).
(fig. 2)

Now you can create shapes! Choose a radius for your rounded corners and you’re ready to go.
Button Styles
Button styles have been evolving as long as the web has and there are an infinite number of styles you could use but I am going to demonstrate a sensible approach that is universal and not heavy on character. The following are tips on using Photoshop’s Layer Styles to create a button like the ones used in the examples.
- Inner Shadow — Pick a bright color, choose the Color Dodge blending mode, bring choke to 100% with a size of 0 and an angle of 90%. This gives a great top edge highlight (tip shout out to Andrew Wilkinson of Metalab Design).
- Inner Glow — Mirror Inner Shadow’s settings and play with the opacity
- Gradient Overlay — Choose colors not too far apart on the color wheel, the gradient should be subtle
- Stroke — A 1px stroke works best. The object is to pick a slightly darker version of your darkest gradient color to “hold things together”.
These are your basic settings for the “normal” state. For the hover state alter the gradient overlay and lighten both colors. The “pressed” state requires a few new styles and a couple adjustments to get that indented look.
- Inner Shadow
- Color: black
- Blend mode: multiply
- Opacity 75%
- Distance 4px
- Choke 4%
- Size: 13px
- Bevel and Emboss
- Style: Outer Bevel
- Depth: 100%
- Size: 1px
- Angle: -90°
- Highlight Mode: Screen
- Highlight Opacity: 40%
- Shadow Opacity: 0%
The CSS behind the buttons
The 3 states of the button are contained in one image so you will use the background-position CSS attribute to control which states are shown for normal, hover and active states. This method is known as sprites and there are many great resources on it. The primary benefit is since all 3 states of the image are loaded in the same file there is no additional loading on hover and active states. The CSS for changing the background image would look something like this:
1
2
3
4
5
6
7
8
|
#bee_button a {
display: block;
text-indent: -5000px;
width: 136px;
height: 41px;
background-image: url(/images/bee_button.png);
background-repeat: no-repeat;
}
|
1
2
3
|
#bee_button a {background-position: 0 0;}
#bee_button a:hover {background-position: 0 -41px;}
#bee button a:active {background-position: 0 -82px;} |

Conclusion
You can see buttons like these in action on the Widgetfinger home page and inside both Hoptoad and Thunder Thimble. They provide a tactile experience for the user and an extra bit of visual feedback when a button has been clicked.