Background: there are several places in our app where we want to display date-oriented information on a calendar. The event_calendar gem looks nice and has lots of reviews, so it's what I'm planning to use. However, it's designed to work with a model. I'm not going to update our existing models to meet its needs, so will create a DTO class and a helper function to construct an array of instances from our existing models.
My question is: where should that DTO class live? It seems like it should be defined inside ViewHelper
, but that will violate DRY as soon as I use the calendar for two models (note: the helper functions will differ, it's just the DTO class that will remain the same).
So, is there a standard place in the Rails directory tree where non-model-related classes live?
Or is there a better/more idiomatic way to do this? One thought that I had was to make my helper function decorate the existing model instances with the methods that event_calendar wants to see.
4 Answers 4
I think the equivalent of the Data Transfer Object you mention is called a presenter in the Rails ecosystem.
On projects with few presenters, I have seen them placed in the /lib
directory, but you might as well create an /app/presenters
directory.
Also check out this blog post on presenters by Steve Klabnik.
-
Not quite: as I read the blog post (+1 for that, btw), the presenter object is the thing that produces the DTO (this became more clear when I read his earlier post).kdgregory– kdgregory2012年03月10日 13:07:05 +00:00Commented Mar 10, 2012 at 13:07
It seems that you would like to use repetitive non model functionality. If I am right, then you can wrap it with Module and put it within app\models folders
You might have a look at the following article http://www.codercaste.com/2011/02/11/10-ruby-on-rails-3-tips-that-will-make-you-a-better-rails-programmer/
I ended up creating a base class in lib
, that defines the attributes and a few helper methods. I kept a class inside the helper, but all it has is an initialize
(that's where the interesting stuff happens). I also have a helper function that does the map
to convert objects.
Reading Steve Klabnik's blog, I came across the following quote, which I think summed up my feelings going into this. I think I've gotten over it.
Maybe it's that lib/ feels like such a junk drawer
If you find you are repeating yourself a lot, you might want to take a look at the cells gem. Cells are basically mini-controllers that are especially useful when creating widgets and the like.
The readme sums it up nicely:
Say you’re writing a Rails online shop - the shopping cart is reappearing again and again in every view. You’re thinking about a clean solution for that part. A mixture of controller code, before-filters, partials and helpers?
No. That sucks. Take Cells.