Ask A Question

Notifications

You’re not receiving notifications from this thread.

What is the best way to house view logic?

Mark Kadlec asked in Rails

I have a view that is showing a list of steps. The steps are being pulled from the db with a status field.

There is a method that I've created that creates custom text based on the status, ie:

def return_custom_text(status)
  ... some code to determine the custom string
end

I already have a ViewModel that is assembling the data and has an attribute called 'steps' that the view will use to list the steps, but I need to add the custom_text to each step.

Should I create a helper method and call from the view, or simply create a method in my ViewModel that loops through the steps and creates a new array with the added 'custom_text' attribute?

I was hoping to avoid helper methods since I'm trying to keep my views as codeless as possible, what is the best practice here?

Reply

Thanks Jack, so you would use a helper like:

Text: <%= custom_text(status) %>

The only con I see with this approach is now you have a ViewModel and a helper file vs keeping all of the logic in the ViewModel.

If that's the best convention though I'll go with it!

Reply

Hey Mark,

I think Jacks answer is the more railsy way of doing this, so if you're worried about convention then that's probably your best bet.

However, you're already stepping outside the normal rails convention space by utilizing a view model pattern, so really your idea of making another method inside your view model probably fits better with your design.

Just my thoughts FWIW, good luck!

Reply

Thanks Jacob, I'm definitely leaning to putting into the ViewModel to keep all Business/View logic in a single entity, was curious what the Rails community's thoughts were.

Appreciate the responses!

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 85,972+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.