Merb Tips 2

_* this content is now outdated and only applied to Merb 0.9_*

I the previous post I covered few useful tips for Merb 0.9. The good news is that Merb should get its wiki setup over the week end!

Here is another batch of hopefully useful tips:

  • In init.rb, you can define a dependency and specify a version number: dependency “merb_fu”, “>= 1.0”

  • If you want to run your application from a subdirectory, once again, in your init.rb file, add: c[:path_prefix] = “/your_prefix” (note, that you can also do that in a specific environment file.)

  • You feel like limiting a route to a specific request such as a DELETE? In your router.rb file add the following:

    1 2

    r.match("/:bucket_id", :method => :delete).to(:controller => "buckets", :action => "destroy")
  • Since we are talking about routes, what about an iPhone only route?

    1 2

    r.match(%r[^/(.+)], :user_agent => /iPhone/).to(:controller => "mobile", :title => "Welcome Apple FanBoy", :action => "show")
  • what about an admin section for my blogposts?

    1 2 3 4

    r.match('/admin') do |admin| admin.resources :blogposts end
  • To finish with the routes, look at the following merb-core spec

    1 2 3 4 5 6 7 8 9

    it "should allow you to restrict routes based on protocol" do Merb::Router.prepare do |r| r.match(:protocol => "https://").to(:controller => "foo", :action => "bar") r.default_routes end route_to("/foo/bar").should have_route(:controller => "foo", :action => "bar") route_to("/boo/hoo", :protocol => "https://").should have_route(:controller => "boo", :action => "hoo") end

You can set custom routes to only work when connected via SSL, that’s just really nice!

  • Other quick tip. Last time we saw how to install locally all the required gems. Well, you can also freeze merb by doing:

    1 2

    merb-gen frozen-merb
  • Another common IRC question, how do I use Merb’s logger. It’s really easy:

    1 2

    Merb.logger.info('our stuff')

Where info is the debugging level you want to send your message to.

  • Finally, today in IRC a Rails user asked how reset a session in Merb. Rails has a reset_session method that resets the session by clearing out all the objects stored within and initializing a new session object. Merb simply uses a hash to store sessions, so session.clear will do it ;)

Feel free to add a comment with your Merb tips or leave a question regarding something you can’t seem to be able to do with Merb.


385 Words

2008-04-08

comments powered by Disqus