Mr eel

Camping: Adding Some Railsisms

I really love Camping. It’s packed full of magic and is just perfect for tiny projects. That said it can be a little obtuse at times and the documentation covers the API, but is a bit light-on when covering actual usage.

So, as a result I’ve spent a lot of time hacking about the code trying to figure things out. The upshot of this is a fair grasp of how the framework works. That means getting to extend it.

Camping.send(:include, SuperFunTime) => weeeeeee!

Now, Camping isn’t Rails. It doesn’t have the same philosophy, so I think it would be a mistake to try and make it into Rails. That said, there are some nice ideas that we can nick and use in our Camping apps.

I want a params hash. Camping has input, which is just a hash of parameters passed in via the query-string or a POST. Rails params however is a nested hash. Using the [] notation in your input names, you can have the parameters automatically nested for you:

patch[version], patch[name] => {'patch' => {'version' => value, 'name' => value}}

So, lets make our own version for our controllers!

module Railsisms
  def params
    return @params if @params
    @params = @input.inject(Hash.new {|h, k| h[k] = {}}) do |hash, key_value|
      if key_value[0].include?('[')
        name = key_value[0].match(/(\w+)\[(\w+)\]/)
        hash[name[1]][name[2]] = key_value[1]
      else
        hash[key_value[0]] = key_value[1]
      end
      hash
    end
  end
end

To use this you include it in your controllers. You can then access it by calling #params. The first time it’s hit parses the content of the @input attribute. Subsequent calls just return the hash.

Posted on June 28th, 2007 | There are 0 comments

Comments

Add a comment

All contents © 2005—2007 Luke Matthew Sutton