Shortest Code Wins
August, 20th 2010The conversation around here has been so great as of late that I thought I’d offer up a challenge for you all. In your language of choice create the shortest and most readable controller method you can which would accept and save a blog post. A few caveats:
- It must be readable, sure everything can fit on one line, but is it still readable?
- It can’t use black magic. Your code must actually function in some system on some framework somewhere. It can be your own framework or a common one like Rails or Cake, but don’t just write
post.saveand be done.
I’ll kick things off with my example:
public function do_save() {
$post = new Post($this->input->post('post'));
$post->save();
redirect('/posts/'.$post->id);
}
That’s how I’d structure things, sure I could have wrote:
public function do_save() {
redirect('/posts/'.$this->post->create($this->input->post('post'))->save()->id);
}
but can anyone actually read and understand that?
So, what’s your code look like? Are you a multiliner or a singleliner?



Comments
Accepts, saves, *and displays*? Above and beyond, Mark.
Posted at 10:39 AM on August 20, 2010
I’m sure there’s a better way to do this, but for now:
def post(request, id):if request.method == "POST" :
p = PostForm(request.POST)
if p.save():
return render_to_response('entry/detail.html', {'post': p})
Posted at 11:21 AM on August 20, 2010
Oh Kenny, where’d all the semicolons go ;)?
One quick question, if you wanted to redirect a user away from your form submission page and back to a “public” URL, I assume that’d be a trivial change, no?
Posted at 11:45 AM on August 20, 2010
That’s what would happen actually, but it’s controlled in a different part of Django. There’s no 1:1 correlation like there would be with CodeIgnite & Rails. URLs don’t map to methods by default.
Posted at 11:58 AM on August 20, 2010
Post a Comment