DEV Community

Matthew McGarvey
Matthew McGarvey

Posted on

Crystal View Context

This article is meant to be more of a public note than anything.

I have found myself wondering why several Ruby gems that allowed you to create HTML in plain ruby still required you to have separate files instead of putting them in plain ol' ruby objects. As I'm working on my Crystal implementation of Roda, it finally occurred to me why. It's to be able to manage scope. All of those languages didn't require calling the methods on anything, the methods were just there. It's because the file is run in the context of a class that provides those messages.

Now why did I put Crystal in the title but only talk about Ruby? Well, we have a context issue in Crystal and we've struggled with it a fair amount. There's ECR which does some fancy macro things but ultimately just copy/pastes the ECR file directly into the place where ECR.render is called. Over in Lucky, though, we make HTML through Crystal code and they are separate objects. One of the pains of that is passing in the HTTP context for things like link helpers and CSRF tokens. Buuuut, if the Crystal code was in a separate, non-Crystal file, we could still have all the functionality of Lucky's html building, but with the context control of ECR.

I am sticking with ECR right now in my library, but I might experiment more in the future. One advantage of this over ECR is that I don't have to do any pre-processing to pull out the fancy tags for embedding crystal into regular HTML.

Discussion (0)