Using maroon to do Injectionless DCI part II

Posted: February 25, 2013 in DCI
Tags: , , ,

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

context :Account_context Account do
   #implement the context

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
  role :greeting do end
  greet do
    p "#{greeting} #{who.say}!"

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 person1, person2,person2).call

In the first version whatever arguments you pass will be passed to new of your context class (in this case to 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


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


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s