Rails conditional CSS in view helper

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>

Answers


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) %>

Need Your Help

PFQueryTableViewController “No Results” Cell

parse.com pfquery

I am using a PFQueryTableViewController to display data from PFObjects but I want to create an alternative cell for when there are no objects to show. I tried doing this but when I return 1 in

Setting CSS Media Type Inline

javascript html css media-type

I am producing a standalone HTML document under the constraint that the document has to be exactly one file. I would like to use CSS to make sure that links in the document are visible and discover...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.