0

I have a simple rails app and I'm trying to write a view helper that does the following.

Compares two values. If the current_month amount is greater than the forecast amount then make the text green. If the current_month amount is less than the forecast amount then make the text red.

I wrote out this simple helper to append text to the output of the the rails method, but I'm unsure of how to inject CSS/styling into this.

def target_hit(forecast, current)
  (if current.amount > forecast.amount
    number_to_currency(current.amount.to_s) + " Yay"
  elsif current.amount < forecast.amount
    number_to_currency(current.amount.to_s) + " No dice"
  end).html_safe
end

I'm pretty proficient on the backend but when it comes to front-end stuff I'm stumbling a lot. Any help would be greatly appreciated.

example view code

<p class='total'>Current: <%= target_hit(@forecast, @current) %></p>
2
  • You can call a helper method from a class. Or in your target_hit method you could use content_tag to define the class. I'd need to see your view to provide an example. Commented Aug 14, 2015 at 22:57
  • @margo I provided a excerpt of my view on how I would call the method. Commented Aug 15, 2015 at 2:55

1 Answer 1

1

The rails helper content_tag http://apidock.com/rails/ActionView/Helpers/TagHelper/content_tag, is useful and means you don't have to use html_safe. I try to move all the logic from the views to helpers to make the view easy to read e.g.

def target_hit(current_amt, forecast_amt)
  content_tag(:p, "#{number_to_currency(current_amt.to_s)} target_content(current_amt, forecast_amt)", class: "total #{target_class(current_amt, forecast_amt)}")
end

def target_content(current_amt, forecast_amt)
  forecast_reached?(current_amt, forecast_amt) ? "Yay" : "No dice"
end

def target_class(current_amt, forecast_amt)
  forecast_reached?(current_amt, forecast_amt) ? "green" : "red"
end

def forecast_reached?(current_amt, forecast_amt)
  current_amt >= forecast_amt
end

in the view, you just call the helper method

<%= target_hit(@current.amount, @forecast.amount) %>
Sign up to request clarification or add additional context in comments.

1 Comment

This is much simpler than what I had came up with on my own. I really like this answer. Will upvote as soon as possible :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.