technicalpickles

Open Source ProjectsCode that Might be Useful to You

Talks I've GivenOn Technologies and Ideas

ThoughtsWhere I Sometimes Write Things

Resume If You Believe In Those

Follow Me On

GitHubIf coding is your thing

TwitterIf you tweet

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

comments powered by Disqus