What is the Rails Presenters folder for? - ruby-on-rails

What is the Rails Presenters folder for?
What goes in this folder?
Why is this folder needed?

presenters is a design pattern commonly reffered to as Model View Presenter(MVP)
This is a derivation of the Model View Controller pattern and is used for creating user interfaces.
It's useful for the Separation of Concerns for making code more DRY.
Here's how Wikipedia describes it
model - interface defining the data to be displayed or otherwise acted upon in the user interface.
presenter - acts upon the model and the view. It retrieves data from repositories (the model), and formats it for display in the view.
view - a passive interface that displays data (the model) and routes user commands (events) to the presenter to act upon that data.
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter
Presenters in Ruby on Rails
Presenters are simple classes that sit between the model and the view and provide a nice, DRY object oriented way of working with complex display logic.
In Rails, the convention is for them to be located in the app/presenters folder
Here is a userful article that explains the pattern and its use in Ruby on Rails.
https://kpumuk.info/ruby-on-rails/simplifying-your-ruby-on-rails-code/

The Presenters folder is where your Presenter code would go. I know, obvious, I'll explain.
The way I think of Presenters and Decorators is as an abstraction of a Model in order to massage the data attributes before they are given to view.
If you are familiar with helpers, well, Presenters are kind of like helpers in the sense that they are getting some data ready for the view, except helpers usually serve as utility methods for said views, while presenters are more about presenting the actual attributes.
This link explains the difference very well: https://awead.github.io/2016/03/08/presenters/
hope that helps.

Presenters de-clutter your views
When people mention presenters in a rails context (as opposed to discussions of Model-View-Presenter, MVC, MVVM discussions etc) they are referring to a situation where things look really complex in your views: there are plenty of if statements everywhere, and it's difficult to read through it all.
Or to adopt an everyday analogy: imagine you have a really messy house, with stuff piled up everywhere - so that it's difficult to walk through. You can think of a presenter as a large garage where you can neatly organise everything. This makes it much easier to walk through your house, and you still have all the utensils that you need.
Getting back to the rails context: Presenters allow you to remove all that complex logic somewhere else: into the Presenter's folder, so that when you read your views, it will be a lot easier to understand from a higher level. The clutter isn't there, the complexity isn't there: that has been transferred somewhere else. If you want more detail, you will have to go to the relevant folder. The logic need not be contained in a folder called "Presenters" but it can be put there by convention.

Related

What's the difference between a controller helper and a concern?

Would concerns help me share logic for partials? I see Rails 4 has the "concerns" folder for controllers, but it's empty on app generation.
DHH wrote a blog on concerns (but I think they are for the model): http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns
I would appreciate a concise example.
Simply put:
Helpers contain methods to be used in views.
Concerns are modules to be included in controllers/models(depending which concern is it) etc.
It's just a folder with code that you could otherwise put in another place if you wanted. We use fancy terms like concerns to get paid more.
Concerns are modules that get mixed into controller or model classes for instance. DHH's post focused on models, but the same applies to controllers. It helps slim down the model or controller classes, and makes it easier to reuse common code across multiple classes.
Helpers are for short presentation-oriented methods that you want to call from your views, or very occasionally from your controllers, maybe.

Rails 3 project structure for UI Models and Data Models

This may be a really stupid question, but I do not have it clear in my mind as to how it is best to manage this so want to put it down here and see what is common practice.
Coming from .net my web applications are never 1 project which is everything, I tend to at least have a data layer project which deals with persisting entities to the database and making these models represent said entity in a DB friendly manner. Then I have my UI project which has its own models which are a representation of the entity for the UI, which may have validation based information and will most likely be a more cut down model only exposing what is needed.
So the main point I am trying to get out here is that although we may have a User entity, the models to represent that may be slightly different in the UI and Data layers...
Now fast forwarding to rails, you create your project and it comes with database connectivity (which I believe can be swapped out to any flavour you want), and validation and a whole manner of other frameworks and functionality. This then seems to imply that I no longer need 2 projects, just 1 as its all included within here and all done for me, so all I need to worry about are making my models.
This is the part where I am a little confused, as lets say I am using ActiveRecord I will need to make my model and inherit from ActiveRecord::Base, then I will need to setup how this model connects to other models etc, so I have my model's data concerns sorted, now I need to setup my UI concerns, about validation and string lengths etc... now where do these go... I am assuming on the same model, but then a model isnt just a simple representation of data, its a blob of stuff containing concerns for databases and views and who knows what else.
It just seems a little odd to put everything within this one place. I know in .net there are plenty of examples where with large object graph representations in the DB the data models are VERY different to UI models, so is it wise to couple them into one model this way, or is Ruby and its frameworks so flexible in this area that you do not have these same problems? If so is there some example or article which can solidify in my mind how you sidestep the normal problems that cause you to separate your concerns to have maintainable code...
=== Edit ===
Just to try and clear up any confusion, in my post when I say my view models and view concerns, I do not mean presentation concerns. I am sorry if it came across that way. What I mean is that I may have (in a normal .net example) a UserStorage model, which has concerns about persisting a User entity. I then in the ui layer have a view which displays many users and one that displays single users in more detail. You may have 2 differing models here a UserSummary model and a UserDetails model, both partially represent a User entity, but are customised for the actual view in question, as you may get to a situation where UserDetails also becomes a composition of a User and a Company entity, which would mean there are 2 storage based classes feeding into 1 view based class.
Within the examples and guides it makes out like you should have 1 view model which deals with these concerns, as well as storage concerns, and in this case it just seems like if I were in the situation where I had a view model that was a composition of a User and Company it would seem odd for this view layer class to worry about its storage, as its never stored as itself, it is stored as 2 separate models in the database/datastore.
This is the REAL problem I am trying to get at here, it seems to be tightly coupling your view to your storage concerns which I am used to being 2 different things which should never be mixed... like putting your main course and pudding on the same plate...
In vanilla Rails, there is no such thing as a "view model".
The models handle all business logic, including query and persistence, association, and validation. You seem to be dismissing validation as a concern of the view, but this is actually a core concern for the integrity of your models: it does belong there.
That's not to say that validation shouldn't happen in the view (client-side) too, but the model has your core business rules and is the place where the validation rules are ultimately checked.
You will want your models to hold most of the logic of your application. This means things like checking if a user is valid or active, finding related records, etc. Pretty much anything that isn't presentational belongs in the model.
In the view, Rails provides helper methods for formatting. These come from modules that are included in the view instance. Helper methods have access to the instance variables of the view (your models) and are used to present them.
In some situations, passing naked models into the view makes it hard to keep things modular and organized. Some people prefer using Presenters to wrap the models before passing them to the view. It can help to organize your code, but it's also an extra layer. Presenters are not standard in Rails, but it's trivial to add this pattern using plain ruby objects or a library like draper if it makes sense for your application.
EDIT: Oh look, a most excellent blog post on just this very topic came up today, from the most excellent Thoughtbot.
In a nutshell:
if it's about the data (storage, integrity, etc.) it goes in the model
if it's about processing/calculating the data (e.g. finding all pending orders) it goes in the model
if it's about presenting the data (pending orders should have a red cancel button) it goes in the view
Since you seem to be an experienced developer, you'd probably benefit from this book http://www.manning.com/katz/ Its geared towards developers that are new to Rails (but not to web programming).
Alternatively, there is a free online tutorial also http://ruby.railstutorial.org/
And of course, the Rails guides are always a good source of information: http://guides.rubyonrails.org/
Not one mention of MVC in your question, you should look into the Model View Controller pattern.
You should also look into how migrations work.

What is the best way to implement skinning in a Rails app

Using Rails, I am building several sites which are very similar. I want to implement these as one Rails app answering to multiple domains, and change what is presented and the processing logic based on the domain name. The areas I need to change/skin per site are:
Views: The fields on a page differ slightly by site. Some sites have more/different fields than others, but there are some that are common across all
Models (which seems best to do this by defining a super class for the main model which varies and implement a subcalss for each site)
Controller logic. There is a lot of similarity but a few small processing differences, including which Model subclass to deal with
CSS (which seems fairly straight forward)
I have already implemented a mechanism which makes the current domain/app name visible to the views, controllers and models.
I was thinking of defining a view partial per site and using ERB logic to include the right one. The controllers seem like the least obvious part.
Any suggestions very much appreciated.
Cheers
Paul
I have implemented something similar for our application, HiringThing (http://www.hiringthing.com)
To do so, we use a before_filter on the application controller that parses request.host and determines what website the request is for. That then sets a variable #site that we reference in views, controllers and models to determine versioning requirements at runtime.

Does this approach to fat model/skinny controller take it too far?

I am afraid that I might be getting lazy.
I am developing a ruby on rails application involving about 8 models relating to two types of users: physicians and patients. Most of the logic is inside the models allowing my controller actions to be very short and concise. Plus, it makes the testing fairly straightforward.
I currently envision at least two controllers and the tests that I am writing lead me to believe that most of my user-facing features can be handled by these two controllers. Sure, I can break this into more sensible compartments-like tests for a patients-controller, physicians-controller, patient-medications controller, patient-lab-results-controller and so on. But it seems to me that the only advantage here is more discreet organization.
On to the question, asides from compartmentalization, what are the reasons NOT to use as few controllers as possible, pack them with lots of actions [disadvantage], but keep the actions skinny [advantage]? Or...to take it to an extreme: Why not with MVC, have a bunch of fat models, and one skinny [albeit long] controller rather than a patient controller/model/views+tests for EACH, physician controller/model/views+tests for EACH, etc?
There's organization, as making everything inside a single controller is possible, it's going to be harder to understand and change. Instead of being able to open a file in your editor and finding the action you're looking for right away, you would be scrolling down the file to find what you're looking for.
This also leads to the God object pattern where everything happens inside a single object that's responsible for everything and everyone working at the project will be changing this same object, leading to an eternal merge hell.
And, on Rails itself, there's the RESTful-ness of the framework. Rails embraces the idea of being RESTful and one of the pillars of this idea are the resources and they can only be easily organized in separate controllers. If you try to place two different resources at the same controller you'll probably end up with crazy routes or crazy controller logic to find out which model is being represented.
If you think your controllers have a lot of repeated code, you can DRY them out using some metaprogramming magic or conventions, but it's really better to have them separated, not only for organization but also to simplify your own future maintenance.
If there's a lot of common controller logic, you might consider abstracting it out into a plugin or module that you can mix in when needed. Or the controllers could inherit from a common base controller (much as all controllers inherit by default from ApplicationController, rather than ActionController::Base).
I would advise against having one gigantic controller; a controller should manage the set of actions which pertain to a single type of resource (or the closest analog possible). This idea is even stronger if you are trying to create a RESTful design, in which each controller typically has nothing other than the basic seven actions (index, show, new, create, edit, update, destroy).
So if you want to have URLs like /patients/52394802/lab_results, I think it makes complete sense to have a LabResultsController. If these controllers are lightweight, awesome. I'm of the opinion that their existence is still justified. This shouldn't stop you from trying to make your code DRY; rather, I would simply try to abstract away the common functionality differently.
That's an impossible question to answer. Controllers are about routes and user interactions and views not business logic. Have as many controllers and actions that it makes sense to have for your links and views!
If your business logic is all in your models then it's simple enough. The main difficulty with logic in controllers is that you can't re-use the logic.
Nothing much more to say really. It's up to you to do what makes sense in your app. e.g. have a search controller to search for stuff rather than adding a search action to your existing controllers is not really about anything more than separation and clarity

ASP.NET MVC - when SRP and DRY appear to conflict

My simplest ASP.NET MVC 2 controllers make calls to my service layer and map view models to entities using AutoMapper. Everything looks fantastic and there is no repeated code.
However, when I get into scenarios where I have similar behavior I have trouble balancing Single Responsibility Principle (SRP) with Don't Repeat Yourself (DRY). An example of this might be the need to add/edit vehicles where some properties/behaviors are shared while others are unique to a specific vehicle.
If I strive for really thin controllers (thus honoring Single Responsibility Principle), I end up having repeated code in both the views and controllers with minor variations (title, field labels, field visibility, dropdown values, selection criteria, etc.).
If I strive for non-repeated code I end up bundling too much logic into a single controller/view and it gets bloated.
What are some ways of addressing repeated code in controllers / views? I'm not talking about database code that can be factored out to a repository. Nor am I talking about business logic that can be factored out to a service layer. I'm looking for tools and/or rules of thumb that will help me produce the best solution in the scenario described above.
You get:
partials
RenderAction
action filters
service layer and helper classes (not HtmlHelper)
model binders
base controllers
dependency injection
So your views can invoke shared partials/actions for similar parts, common data can be prepared by action filters, database access code can be hidden in smart model binder, or you can have parent controller that child controllers override with specific tweaks. And, of course, good old service layeres, where you just extract common code into helper/static methods, or, better, inject specific implementations.
That's nothing new, same old tricks.
Or, maybe, your controllers do too much works? This is where stuff above also helps. ASP.NET MVC has very good tools to hide infrastructure-layer code and move it away from controllers. And if it's not infrastructure - it probably belongs to domain layer. There you can use inheritance, composition and other OOP tricks.
Specific example. Suppose your controllers should set few properties in a different way.
You can have your views to do this, if it's mostly formatting or choosing what properties to show
You can have your entities to have virtual methods - i.e. refactor code to move decisions to domain layer instead of controllers
You can have helper ViewDetails classes that will take your entities and get the data based on for what you need it; this is a bit of a dirty trick but sometimes useful; you delegate decision to another "strategy" class
You can use action filters to add this data to ViewData, or to tweak specific ViewData.Model types (look for some interface of it).
You can have abstract controller, where children pass implementation details to the base constructor like (): base(repository => repository.GetSpecificData())
And so on. I actually use all of them in appropriate places.
You are worrying too much about SRP and DRY. They are principles only and are not always right. SRP and DRY are good if they make your code more maintainable, but if they are in the way then ignore them. MVC is similar. It is useful in simple small desktop applications but is not appropriate for web applications. Web Forms is much better for the internet world while MVC is something from the 1980s.
I recommend you to use SRP over DRY in those cases. I wrote here a detailed answer.
In short both are rules which help to keep your code maintainable. DRY is a low abstraction level mechanism, while SRP is a high abstraction level. By maintain an application the high abstraction level structure is more important than the low abstraction level.
In your case I don't think it is necessary to give up DRY.
An example of this might be the need to add/edit vehicles where some
properties/behaviors are shared while others are unique to a specific
vehicle.
Many design patterns can help in this case. You can use decorator, composition, and so on... combined with builders for the different types of vehicles.
I found that ApiEndpoints is very good for this. You create a class for each controller method. A little more code, but I think it's very clean.

Resources