Device Extension

One of Ruff driver principles is only basic features is implemented in a driver. For instance, a LED driver provides only turnOn, turnOff and query(isOn) functions.

$('#led').turnOn();
$('#led').turnOff();
$('#led').isOn();

But, what if I need more features? For example, I need a toggle function: turn on the LED if it is on; turn off the LED, if it is off.

Using extend

Every device object in Ruff has a extend function, which is used to extend the object self:

$('#led').extend({
toggle: function() {
if (this.isOn()) {
this.turnOff();
} else {
this.turnOn();
}
}
});

The argument to extend is a plain JavaScript object, whose function will be part of the target device object. That is why you could use this to access the function in device object.

Defining trait

toggle is a regular function which could be applied to many different device objects. If we want to use it in many different projects, we could define it as a module. But how could we know there are required functions in every target device object? We define it as a trait.

trait is a common language feature to extend object behavior. Ruff SDK provide a API to define trait.

In this case, we’ll define a trait in which there is a toggle function, and there are turnOn, turnOff and isOn functions in target object.

The following is trait for toggle.

var trait = require('trait');

var ToggleTrait = trait({
toggle: function() {
if (this.isOn()) {
this.turnOff();
} else {
this.turnOn();
}
},

turnOn: trait.required,
turnOff: trait.required,
isOn: trait.required
});

The argument to trait is a plain JavaScript object,

  • plain JavaScript function will be member function of target object.
  • any function annotated with trait.required will be used to check if it exists in target object.

You can use the trait to extend device object. A trait can be passed to extend:

$('#led').extend(ToggleTrait);

If required methods are missing, a exception will be thrown.

Trait can be published to Rap Registry as a module.