Options processing

Portlet title

The dashboard already looks great.

The widgets need customized titles, though. Being all about encapsulation, Apotomo naturally provides a way to pass options into widgets from outside.

app/controllers/dashboard_controller.rb (snippet)
 4  has_widgets do |root|
 5    root << widget(:twitter_widget, 'parrot', :display_form)
 6    root << widget(:trashbin_widget, 'bin', :display, :title => "Trash tweets here!")
 7  end

We can provide arbitrary options in the widget method (line 6).

app/cells/trashbin_widget.rb
 1class TrashbinWidget < Apotomo::Widget
 2  responds_to_event :drop, :with => :trash
 3  
 4  def display
 5    setup!
 6    
 7    render :layout => 'portlet'
 8  end
 9  
10  def trash
11    setup!
12    
13    Tweet.find(params[:id]).delete
14    trigger :tweetDeleted
15    
16    update :view => :display
17  end
18  
19private
20  def setup!
21    @title = @opts[:title]
22  end
23end

The widget can subsequently access the @opts hash and process its parameters (line 21). It also uses params to access request parameters (line 13). You may use these variables, however, there is a safer approach in Apotomo that we'll discuss shortly.

Note that we have to call setup! in the start state as well as in the trigger states, as our widget is stateless.

Using hooks

Fortunately, Apotomo already has a hook for exactly that job.

app/cells/trashbin_widget.rb
 1class TrashbinWidget < Apotomo::Widget
 2  responds_to_event :drop, :with => :trash
 3  
 4  after_initialize :setup!
 5  
 6  def display
 7    render :layout => 'portlet'
 8  end
 9  
10  def trash
11    Tweet.find(param(:id)).delete
12    trigger :tweetDeleted
13    
14    update :view => :display
15  end
16  
17private
18  def setup!(*)
19    @title = param(:title)
20  end
21end

The after_initialize hook (line 4) will execute all attached callbacks after the widget was created. It is somehow comparable to a before_filter in Rails controllers.

A cleaner parameter lookup

It is usually safer to use param for parameter access. This method provides both request parameters and variables from widget (line 11 and 19), where the latter overwrites parameters from the request in a name clash.


blog comments powered by Disqus