I thought it might be fun to start posting about some of the little known features in Mack. There are a treasure trove of them in there, so let’s pick a couple and start there.
<%= render(:url, "http://www.mackframework.com) %>that will render the contents of http://www.mackframework.com into your view. You can also do ‘local’ urls.
<%= render(:url, "/users/1") %>will make an internal request to your application and render the results of “/users/1” into your view. The optional 3rd parameter to render allows you to do things like set the HTTP method:
<%= render(:url, "/users/1", :method => :post) %>or add parameters you want to pass to the URL you want to render:
<%= render(:url, "/users/1", :method => :post, :parameters => {:id => 1}) %> Mack::Routes.build do |r| r.resource :users r.home_page "/", :controller => :default, :action => :index r.handle_errors ArgumentError, :controller => :problems, :action => :arguments r.handle_errors DataMapper::ObjectNotFoundError, :controller => :problems, :action => :not_found r.defaults endWhat’s going on with r.handle_errors you ask? Well, first we tell the routing system which error we want to capture in our controllers, DataMapper::ObjectNotFoundError, then we tell it which controller and which action we want to handle that error.
When an exception is thrown during a request Mack checks to see if that exception has been registered, if it has been then the request gets forwarded to the defined controller and action for handling. So in the above example if a DataMapper::ObjectNotFoundError is raised, the request will be forwarded to the ProblemsController, not_found action.
One of the really nice things about this is that you have access to the original request, so you can’t get the page the person was trying to access, any parameters that were passed, etc… You also have access the exception itself with the caught_exception method.
To do a server-side redirect in Mack is very easy. Here’s what a client side redirect in an action would look like:
redirect_to(users_index_url)To make that a server-side redirect you would simply pass an extra option to the redirect_to method:
redirect_to(users_index_url, :server_side => true)
Mack::Routes.build do |r| r.old_foo "/my_old_foo", :redirect_to => "/my_new_foo", :status => 301 endFrom now on anything comes in to “/my_old_foo” will be redirected to “/my_new_foo” with a status of 301.