Options processing apotomo-1.0

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)
 3  has_widgets do |root|
 4    root << widget(:twitter)
 5    root << widget(:trashbin, :title => "Trash tweets here!")
 6  end

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

Looking up options

Passing a configuration hash into the widget is a very common task. It’s so common that it is built into the widgets itself.

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

Widgets can easily access their configuration data using #options (line 21). In states triggered by an event they can use the event object to access request parameters (line 13).

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/widgets/trashbin_widget.rb
 1class TrashbinWidget < Apotomo::Widget
 2  responds_to_event :trash
 3  
 4  after_initialize :setup!
 5  
 6  def display
 7    render :layout => "portlet"
 8  end
 9  
10  def trash(evt)
11    Tweet.find(evt[:id]).delete
12    trigger :tweetDeleted
13    
14    update :view => :display
15  end
16  
17private
18  def setup!
19    @title = options[: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.


blog comments powered by Disqus