My favorites | Sign in
Project Logo
                
Search
for
Updated Apr 01, 2008 by matt.zukowski
Labels: Phase-Implementation, Example
ActiveResourceClientExample  
Sample code for talking to Taskr using Ruby's ActiveResource

Introduction

The easiest way to talk to Taskr in Ruby is using the ActiveResource library. ActiveResource -- part of the upcoming Rails 2.0 -- is an abstraction layer providing an ActiveRecord-like API for RESTful resources.

ActiveResource is available as a RubyGem. To install it:

gem install activeresoruce

Defining the Proxy Class

First, we have to define our proxy class for the Task object:

require 'rubygems'
require 'active_resource'

class Task < ActiveResource::Base
  self.site = 'http://taskr.example.com'
end

If you have basic authentication enabled for your Taskr server, your site URL should be something like:

  self.site = 'http://username:password@taskr.example.com'

Okay, now we're ready to start working with Tasks.

Retrieving the list of all scheduled Tasks

tasks = Task.find(:all)
tasks.each {|t| puts t.inspect}

Retrieving a specific Task

Lets say we want to retrieve the Task with id 123:

task = Task.find(123)
puts task.name

Creating a new Task

Here we will create a Task that will execute two Ruby actions every 10 seconds:

task = Task.new
task.name = "My Example Task"
task.schedule_method = 'every'
task.schedule_when = '10s'
task.actions = [
    {:action_class_name => 'Ruby', :code => "puts 'Hello World!'"},
    {:action_class_name => 'Ruby', :code => "puts 'Goodbye!'"}
  ]
task.save

Note that the list of actions is specified as an Array of Hashes. Each Hash represents an action, with the :action_class_name specifying the action type (see BuiltInActionTypes) and the remaining key-value pairs specifying the list of parameters for the action. In this case the two actions will each execute the Ruby code given in their respective :code parameters. The first action will print out the string "Hello World!" and then the second will print out "Goodbye!". Actions are executed one by one, in the given order, although this can be overridden by specifying :order values for each action Hash.

Once task.save is called, the new Task data will be sent to the server, and if the server accepts it, the Task will be scheduled for execution according to the given schedule method and timing.

Deleting a Task

To delete the task we just created:

task.destroy

Or to delete a task with some arbitrary ID:

Task.delete(123)

Sign in to add a comment
Hosted by Google Code