Technical.Web

Technical.Projects

Jeweler is the GitHub recommended way to generating and maintaining RubyGem projects.

Daywalker is a Ruby library for accessing data about congressional districts and legislators using the Sunlight API.

Technical.Stats

Meet Merb: Action methods taking arguments

Have you ever written a controller action like:

class PostsController < ApplicationController
  def create
    @post = Post.new(params[:post])
    @post.save
  end
end

Notice how we yank something out of the request parameters? Wouldn’t it be nice if you could just define that as an argument to the action method?

Well, merb-action-args does exactly that.

class Posts < Application
  def create(post)
    @post = Post.new(post)
    @post.save
  end
end

Superficially, for this example, there isn’t really much of a difference. But, I do feel like it shows your intent more clearly. It basically says, “The create method takes a post.”

How does it work internally? It seems to be using ParseTree voodoo.

When an action is about to be called, the method arguments are looked up. Then, for each argument is used as a key of the params hash in turn. Finally, the action is called with the appropriate arguments.

If you want to actually use it, you need to install it and add a bit to config/init.rb:

gem install -y merb-action-args

Note: this is for merb-0.9.0, which is a ‘developer-only’ release so it’s not available from rubyforge yet. See Michael Ivey’s post about how to install.

dependency "merb-action-args"

If you want to hack on merb-action-args, it’s part of merb-more, which is hosted on GitHub

blog comments powered byDisqus