In the first part of this series we looked at how to install Moby maroon and how to write a simple context with roles. In this post we are going to look at two simple aspects of maroon. The first one is if you wish to have a base class for your context. In the below example the Account class is used as the base class for the context. This will seldom be needed when doing pure DCI but it is possible to do it when the need arises
class Account attr_accessor :account_id end context :Account_context Account do #implement the context end
The second aspect is how to define a default interaction. In the example from the previous post in this series. There’s just one interaction and it might be worth your while to be able to use the context where you would otherwise have used a callable construct
context :Greeter :greet do role :who do say do self end end role :greeting do end greet do p "#{greeting} #{who.say}!" end end
You can now use this context in two different ways where a callable construct is needed. Though you can’t transform this to a proc it still servers as a continuation where you can invoke call. The two options are
Greeter.call person1, person2 Greeter.new(person1,person2).call
In the first version whatever arguments you pass will be passed to new of your context class (in this case to Greeter.new) and the default interaction will be invoked on the newly instantiated context object. If you pass more arguments than new expects then the remaining arguments will be passed to the interaction. In the second version where the context object is explicitly constructed any argument passed to call will be forwarded to the default interaction. It’s worth mentioning that you can pass both a base class and a default interaction in which case you would pass the base class as the second argument and the default interaction as the third. In that case you can either pass the Class object as in the previous example or pass a symbol/string representing the name of the class and the name of the interaction.
context :Account :Owned :balance do
and
context :Account Owned :balance do
Have the same result. A context class called Account is defined. It derives from Owned and the default interaction is called balance. As a final remark all the examples in this post has used context rather than Context::define. to use context you’d need to require ‘maroon/kernel’ which adds a method to Kernel called context. context simply delegate to Context::define so the result is the same either way