Two Step View Pattern - ruby-on-rails

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?

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:
XML == (XSLT) ==> XML
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:
Rails Template == (Rails) == > View-Template
View-Template + JSON-Data == (vue.js/KnockoutJS/Ractive.js/React) ==> HTML

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).

Related

30Bees/Presta 1.6 shop translation in frontController

I am trying to add a few translations to the frontend of our module. When the translations are in the .tpl files they do get rendered. However no translation fields get shown in the backend my code for the .tpl files is:
{l s="Text" mod="myModule"}
I also do need to do some translating in the FrontControllers (mainly Error handling and feedback for serverside validation).
In the AdminController I simply use $this->l('Text'); which works. However, in the FrontController this is not available. I've checked the ControllerCore and FrontControllerCore, l() is not defined in those and only available in AdminController.
Can anyone give me a detailed explanation of what I need doing? All my research on the web always points to $this->l() being the thing to use...
When using translations in tpl files you need to use single quotes not double quotes.
{l s='Text' mod='myModule'}
As for front controllers... well if you're using custom module controllers as in controllers that extend ModuleFrontController you can use
$this->module->l('Text');
And if you're not using those controllers then... start using them.
Some things might be different since thirtybees is a fork of PrestaShop but I guess translation mechanism is the same.

Providing fake data to liquid to render a preview of a template

I have created the ability for users in my system to edit a liquid template that is eventually rendered and turned into a PDF. I would like some ideas as to what the best method would be to create some mock objects to feed the template so as to create a preview for them to see what the final result of their template modifications will be.
The collection of objects passed to the template when it is rendered in real life is fairly complex so I'm thinking at this stage that I can either try and build a temporary model with dependencies in memory, or create some structs that pretend to be the models in question and pass those to the template instead.
Another way could be to instantiate all of this from a yaml file.
Any ideas welcome :)
If you trying to create objects, why dont you use a factory? Are the objects part of the database? You could always use seeds.rb to seed the database with some demo data.
I ended up using a YAML file to build up the structure I needed. It seems that liquid will take a hash of values (and other hashes) instead of the actual models with relationships no problem, so I didn't even need to instantiate the models.
Will happily post an example if anyone is interested.

In Ruby, how can I inspect the class generated by a .html.erb template?

When doing J2EE development, I find it handy for debugging to view the Java classes that are generated by the JSP compiler.
How can I do the equivalent in Ruby? Since it is all in memory, it won't generate a file that I can view. I believe it's the ERB module that generates the corresponding object for a template, so how can I actually view the object? Can I drop a debugger statement somewhere and use rdb? Is there some configuration value I can tell it to dump the object definition? I'm using rails, in case that makes a difference.
I don't think rails generates a class for your view. It basically calls eval after processing the file. Or do you mean inspecting the erb object while it's parsing your template?
If it's the latter you can find erb.rb in lib\ruby\1.9.1 I'd imagine you could just drop a debugger statement throughout that file.
I always make a habit of adding the following to my views (layout) which allows me to inspect or debug the parameters being used by the view in question.
<%= debug(params) %>
This will format all the parameters in yaml and display them in a Hash format.
Have a look at the method in the source code to get a better understanding. SOURCE
There are some differences compared with the Java way due to language differences.
Most template libraries for Ruby follow these steps when compiling/optimizing:
The template is compiled into Ruby source code -- not a class but a long procedure that appends to a string buffer while traversing the logic of the original template.
This ruby code is evaluated in order to be bound for later reference, preferably within a method body. This way, it is only parsed once by the interpreter.
The method (or other context) containing the logic of the parsed template is invoked to render it.
Anyway, the compiled template code therefore looks a lot like a much noisier version of your original template, and will generally not help you debugging, unless you're debugging the template language itself.
Anyone interested in template language implementation might enjoy a look around the Tilt code (use different template languages with the same rendering interface and optimization), and Temple (a great template language meta-implementation).

who's faster mvc2's Templated Helpers or mvccontrib's Input Builders

anybody knows which ones works faster ?
The Embedded Resources of the Input Builders are servered through the WebFormView engine. When your application is set to debug=false in your webconfig the view engine caches the view, so it is only loaded from the assembly once. The real reason why the input builders would be a little bit slower is that they use a master page to reduce the HTML you maintain. The Editor Templates will produce an input for example. The equvilent Input Builder will produce a label, input, and the html 'chrome" around the two so that you can specify it once and have it applied to every form that uses the input builder. The input builders are really for applying a convention for how your forms markup is built and it does it in a way that gives you control but also keeps your html fragments "DRY" (dont repeat yourself).
Like everything there are tradeoffs. For the input builders, you trade off some runtime performance for developer productivity. At the end of the day if you needed to have a super performant form on a public website, your best option would be to server a static html file that posts to an MVC Action.
Your answer depends on where you load your views pages from.
Templated Helpers have a slight edge because without any view overrides they are manipulating strings behind the scenes to produce html output.
Input Builders load views through embedded resources or through the traditional file system which will always be slightly slower than hardcoded string manipulation.
The code for both is similar and do basically do the same amount of reflection and metadata processing. Without any file or resource loading complications they both run at < 1 ms.
With customized template sourcing via embedded resources or file system calls your performance loss will be the same for both.

Would you like ASP.NET MVC view engine in which a view is created entirely in Code?

Recently I created a spike of a view engine, in which views are plain classes, and the content is created by using funny using-scope blocks.
The code together with a simple sample site is available at http://code.google.com/p/sharp-view-engine/
Here I'd like to hear your opinions regarding such an idea. Is it completely weird or maybe someone likes it?
I would actually not like that.
I can agree with DSLs (such as a Parser-Combinator or for generating XML Nodes in a data-context), but in this case I think that too much is being put in code that. And, in the end, this just complicates boundaries and leads to hard-to-maintain code. (You can already do the same, but with more verbosity just using the "standard" Web Controls. You can always use {subblock} in C# to limit a variables scope.)
The approach I prefer to use is templates with bindings (but no "code in templates"). That makes it easy for the "designer" (hopefully not me, or the next person to come along and) edit the layout of the view how they see fit. However, the core logic (the available controls and bindings) are kept in the code -- uncluttered. (Another advantage with the templates is that if they externally housed they do not require a recompile for every little change.)
Simplicity and maintainability are like ... zen.
This is an interesting idea taken to the extreme I'd say. At my shop we're using html conventions for pretty much everything except our layout. The only real html we have in the project is our Spark master page. For generating the content itself we use a convention engine that that spits out a semantic html model. (We're using the HtmlTags library from FubuMVC to build the semantic model.)
An example convention for rendering a multiline text box looks like:
public static HtmlTag Build(ElementRequest req)
{
return Tags.TextArea
.Rows(6)
.Id(req.ElementId)
.Attr("name", req.ElementId)
.Text(req.StringValue());
}
These conventions get triggered from reflecting on the view model (or we can manually call them from a helper method). The output is rendered (via ToString()) into the content section of our master page. We're joking that pretty soon we won't even need a view engine.
ps here's how we handle nesting. (Your using blocks look cluttered!)
return Tags.Div.Nest(
Tags.Button("save").AddClass("positive"),
Tags.Span.Text(" or "),
Tags.Anchor.Text("cancel").AddClass("negative")
);
Nest() is an extension method that simply takes a params array of HtmlTag and appends them to the parent's children collection.

Resources