Blog

Friday, November 30, 2012

Have you tried ctags with Vim?

After reading Mislav Marohnić's excellent post on Vim, I decided to add ctags to my development environment. What does it buy you? It allows you to jump to method or class definitions with these commands:


Setup is pretty easy:


You can generate tags with:


But you probably won't want to do all that manually. As Mislav points out in his post, Tim Pope shows us how to automate tag generation with git hooks.

I've been using ctags this afternoon and already it has turned Vim into a completely different editor for me.

Monday, November 12, 2012

Using Google Site Search for Content Sites: Things to Keep in Mind

I've used Google Site Search for a couple of unstructured content sites (opposed to applications or structured content such as catalogs) and pretty happy with it, but there a certainly some things you should be aware of before committing to this service:

  • The service's crawler works the same on Google.com. This means, it will only index publicly available pages that it can access. So you cannot use it on password-protected staging sites.
  • If you consider removing the password from the staging site you won't want to do that either, as your site must be registered with Google Webmaster tools, so your staging site will eventually end up in the Google.com index. But there's also another issue.
  • Indexes to URL's contain the domain of your site, so you can't index your staging site, then hope to use that index in your live site.

If you're re-launching an existing site -- your only option is to enable search after you have made that site publicly available via the production domain. If it's a new site, and you have the option, make the site publicly available a couple of days before hand and index the site. Google Site Search provides on-demand indexing, updating the index within 24 hours.

When indexing the site, you have three options for supplying URL's:

  • Individual URL's only
  • URL's linked from a specific page or Sitemap
  • URL's in a Sitemap only

Again, you must have your site registered with Google Webmaster Tools for the indexing to work.

For more information on indexing checkout Custom Search Help documentation.

Friday, October 26, 2012

Domain Patterns are Alexandrian Patterns

It's been a while since I have posted on this blog. So just to let you know that I'm still alive, this is what has been keeping me occupied. It's best summed up by a quote from the book Object Thinking by David West. This is a must read for any Rails developer who is following the object-oriented Rails culture.

Patterns most useful to object thinkers should be derived from the problem domain, just as objects are. They should facilitate thinking about co-ordination and scripting of objects or about useful ways of assembling objects into components or applications. They could be considered Alexandrian patterns. Few of the patterns (about 6 of the 23) presented in the GoF book satisfy this demand. Martin Fowler’s book on Analysis Patterns presents examples derived from a domain and is much closer to Alexander’s intent than the GoF book.

My intent is to post more on Domain Patterns in a Rails context in the near future. We'll see.

Friday, March 9, 2012

Testing Terminology: Spies, Stubs and Mocks

When referring to the definitions of Spies, Stubs and Mocks I like to return to XUnit Test Patterns:

  • Test Spy: "We use a Test Double to capture the indirect output calls made to another component by the SUT for later verification by the test."
  • Test Stub: "We replace a real object with a test-specific object that feeds the desired indirect inputs into the SUT."
  • Mock Object: "We replace an object the SUT depends on with a test-specific object that verifies it is being used correctly by the SUT."

You may have noticed that a Spy and Mock seem to have similar definitions, and do serve similar purposes, however Mocks specify expectations up-front and don't require assertions in contrast to Spies, that verify after the fact. Here's an example that compares Rspec Mocks with Bourne's Spies:

SUT is an abbreviation for System Under Test.


The above patterns are collectively know as Test Doubles: "We replace a component on which the SUT depends with a test-specific equivalent." Rspec's built-in mocking library includes a double method/alias, see An Example using RSpec double, mock, and stub.

Double-Ruby (RR) is another example of a test double framework implemented in Ruby.

Sunday, February 12, 2012

Heads up: Use spork-rails if you want to use spork 1.0rc in your Rails project

If you are using Spork 1.0rc in your Rails project and wondering why your controllers etc are not reloading, it's because this functionality has been extracted to the spork-rails plugin gem. Remove the spork reference from your Gem file and add 'spork-rails' instead. spork-rails will include spork 1.0rc as a dependency. This follows the convention for other gems such as rspec-rails and factory_girl_rails. Note spork-rails follows the versioning of minor Rails versions. For example, the current version is 3.2.0, compatible with Rails 3.2.x down to 3.0.0.

Tuesday, January 3, 2012

Some rules to remember when writing Ember.js code

  • Display logic only goes in the view layer
  • Never modify the DOM in View API
  • App logic only goes in the controller layer
  • Limit custom code in the controller
  • Domain logic only goes in the model layer
  • Server calls belong to the model layer
  • Only cross layers going up (V -> C -> M)
  • Never observe across layers

From Sproutcore Training: Part 2 - Core Concepts

Saturday, December 24, 2011

Your Rails Application is Missing a Domain Controller

The mantra of Skinny Controller, Fat Model reminds us to keep our business logic in our models, not in Rails Action Controllers. We know Action Controllers, sub-classes of ActionController::Base, are only responsible for delegating service requests to the domain layer. These models, which encapsulate this business logic, forming the domain layer, represent entities such as a person, place, event or thing. They are often, but not always, mapped directly to database tables through the inheritance of ActiveRecord::Base. When we develop our domain layer for our complex Rails application, purely with models representing entities, we encounter two problems:

Incoherent domain API

When Action Controllers interact with model entities directly, the API to the domain layer becomes clouded. It is unclear what services the domain layer offers and how the UI should request those services. Rail’s ActiveRecord exasperates the issue, for example, there are several ways to create and update model entities and their associations.

Bloated domain models

Business logic that is workflow-oriented involving multiple entities is assigned to a single entity, bloating it’s responsibilities. It becomes difficult to differentiate the entities in the domainrepresenting what the system is, from the use cases or workflow representing what the system does1.

The solution is a Domain Controller. A Domain Controller is responsible for co-ordinating service requests from your Rails Action Controllers. A Domain Controller can come in two flavours, a facade or a use case.

A clarification on terminology: Throughout this blog post I will refer to the typical Rails model as a Model Entity, meaning a model that represents a person, place, event or thing.

Facade Controller

A Facade Controller represents the overall system that encapsulates the domain layer. For example a Catalog object can act as facade for the domain layer containing taxonomies, taxons, product groups, products and variants.

Without the Facade Controller, our service requests to the domain typically look like this:

Product.active
Taxon.active.find(1)
Product.create(:name => 'Ruby Meta-Programming')

With a Facade Controller instance, in this case, a catalog object, service requests appear as the following, delegating to the appropriate Model Entities:

catalog.fetch_products
catalog.fetch_taxon(1)
catalog.create_product(:name => 'Ruby Meta-Programming')

The Facade Controller provides a clear, explicit interface into the catalog domain layer that a programmer can grok within seconds.

Use Case Controller

A Use Case Controller is useful for more complex workflows. They are also helpful when a Facade becomes bloated and you wish to split the incoming service requests across multiple Domain Controllers. It’s important to note, you can use more than one Domain Controller for your application.

Let’s look at an example. The code below represents the processing of a Payroll2. Often this type of workflow logic gets placed in a Model Entity that it doesn’t belong to or worst, left in a Rails Action Controller.

date = Date.today
employees = Employee.active
employees.each do |e|
  if e.pay_date?(date)
    pc = PayCheck.new(e.calculate_pay(date))
    e.send_pay(pc)
  end
end

So what object is responsible for this workflow logic? We know a Rails Action Controller isn’t a candidate. Its responsibility is to handle HTTP requests and delegate to the domain layer. Neither the models Employee or PayCheck are valid candidates. They represents the entities in our domain layer. Therefore we, require a new object PayDayService to encapsulate the logic, a Use Case Controller.

class PayDayService
    def initialize(date=Date.now)
      @date = date
    end

    def call
      Employee.active.each do |e|
        if e.pay_date?(@date)
          pc = PayCheck.new(e.calculate_pay(@date))
          e.send_pay(pc)
        end
      end
    end
  end

The benefit of this approach is that we have encapsulated this workflow logic without bloating existing Model Entities and allows the reuse of this logic in different contexts.

Domain Controllers in a Rails Application

When an application has multiple Domain Controllers I place them in a dedicated directory under app called services to keep them separate from the Model entities in app/models. This helps communicate that Rails Action Controllers should delegate to the Domain Controllers, not directly to Model Entities. The Domain Controllers and Model Entities together, represent the domain layer of the system. I have also discussed extracting the entire domain layer from the Rails framework, but that’s another discussion. Let’s keep this blog post civil for now!

I hope the Domain Controller pattern provides you with another tool for modelling your domain, reduces the coupling with the UI, and provides a clean API to your application logic.

Further Reading

If you are interested in learning more about Domain Controllers and Services, check out the following resources:

  • Applying UML and Patterns by Craig Larman. Craig includes the Controller pattern as one of the General Responsibility Assignment Software Patterns or Principles (Grasp).
  • Architecture the Lost Years a presentation by Robert Martin discusses modelling your application using Interactors and Entities. Interactors_ (which I have used the name Domain Controller) contain application specific logic, and Entities (which I have use the term Model Entities) contains application independent logic. Martin choses to use the term Interactors over Controllers to avoid confusing with Model-View-Controller (MVC). I prefer to use Domain Controller or Service to differentiate from Rails Action Controllers as I just can’t get my head around the term Interactors.
  • Object-Oriented Software Engineering—A Use Case Driven Approach by Ivar Jacobson introduced the concept of interface, entity (Model Entity) and control (Domain Controller) objects over two decades ago. Robert Martin often refers to Ivar Jacobson when discussing application architecture.
  • Patterns of Enterprise Application Architecture by Martin Flower discusses the concept of a “Service Layer” to give the domain layer an explicit API.
  • Domain Driven Design by Eric Evans. Evans discusses the concept of Services for when “some concepts from the domain aren’t natural to model as objects”.

Footnotes:

  1. “What-the-system-is” and “What-the-system-does” terminology is from the book Lean Architecture by James O. Coplien and Gertrud Bjørnvig.
  2. Logic based on the Payroll case study in Robert Martin’s Agile Software Development.

Please note this blog is no longer maintained. Please visit CivilCode Inc - Custom Software Development.