Two Step View Pattern

1.2k views Asked by At

Martin Fowler's PoEAA catalog is like a repository for Ruby gems and Rails modules, for example the ActiveRecord ORM from Rails is based on Fowler's ActiveRecord, and the DataMaper gem is based on the Data Mapper pattern. Are there any useful implementations of Martin Fowler's two-step view pattern in Ruby, e.g. in combination with a template engine?

2

There are 2 answers

2
James Mason On

This is a new pattern to me, but I can two ways to conceptualize it. The core of the pattern seems to be building an intermediate representation first, then run it through a formatting step. In each case, the outcome is a view that looks identical regardless of which class of ActiveRecord model is being displayed.

Option 1: Intermediate Ruby Object

Using a Presenter library (Draper, ActiveDecorator, roll-your-own), you can normalize multiple ActiveRecord classes to a single public API. Then you write a single view template that can render objects with that API.

In this case you create a single view template plus one Presenter object for each ActiveRecord class you need to render. If you need to add new data to the page, you have to touch the template and all of the Presenter classes.

Option 2: HTML + CSS

It's odd, but I think HTML is a valid format to represent data, and could be considered as an intermediate, unformatted representation.

In this case you create a view template (probably a partial, possibly polymorphic) for each ActiveRecord class that produces (nearly) identical HTML. Then you use a CSS component framework to "format" the HTML into identical renderings. The HTML doesn't need to be strictly identical, as long as it all conforms to what your component framework is expecting. Adding data here means changing each view template (the CSS usually won't need modification).

I think both of these approaches are valid. The second feels more "rails-y" to me, but I think it's a departure from the spirit of the pattern, even if it technically conforms (which might be debatable).

0
0x4a6f4672 On

The pattern turns domain data into HTML in two steps. It is particularly interesting if you want to compose your views into decoupled, reusable view components.

One possible solution to implement the two step view seems to be an XSLT transformation, for example with XML and Nokogiri. This means to create an intermediate xml representation of the page:

  1. XML == (XSLT) ==> XML
  2. XML == (XSLT) ==> HTML

A second possible solution is to use a JS template engine like vue.js, KnockoutJS, Ractive.js or React. Rails does the first step and creates an intermediate view, the JS template engine the second:

  1. Rails Template == (Rails) == > View-Template
  2. View-Template + JSON-Data == (vue.js/KnockoutJS/Ractive.js/React) ==> HTML