开发者

what is the ruby/rails/DRY/MVC way to display a color-coded matrix of data

开发者 https://www.devze.com 2023-03-09 02:51 出处:网络
Up until now the MVC separation hasn\'t given me any big problems, but I have to admit the \"right\" ruby/rails/dry/mvc way to tackle color-coded display of tabular data has eluded me.

Up until now the MVC separation hasn't given me any big problems, but I have to admit the "right" ruby/rails/dry/mvc way to tackle color-coded display of tabular data has eluded me.

My app has a page that shows 7 columns (days of week) with 20 rows of data (20 different products) that ranges from 0-10开发者_C百科0 in each cell. Each value is an average of between 50-500 rows in the database.

So the table is displaying 7x20=140 separate 'average' calculations representing up to 500 rows of data each.

Because of the amount of data being shown to the user, we need to color code the cells based upon the value: <25 = red, 25..75 = yellow, >75 = green

our method that does the calculation is product.get_daily_average(date)

We're using HAML, btw.

The problem I have is figuring out where to put the code that specifies the color to apply to each cell...

...should there be if/then code to set the cell style (color) in the View? Is this a logical place for a Helper? Or should the model method that fetches the data "return" the html snippet with the color-code + data (instead of returning the value and letting the view handle the color)?


This is normally the type of thing that you would put in a helper method.

In your view you'd do something like this (sorry, don't know haml, this example is with erb)

<%= daily_average_cell(product) %>

And then in a helper

def daily_average_cell(product)
  value = product.get_daily_average
  color = daily_average_color(value) # probably just make this method right here in the same helper module
  content_tag(:td, value, :class => color)
end


View helpers generally go into the file in app/helpers that corresponds to the controller rendering the views. For example (simplified for brevity):

app/helpers/product_helper.rb:

module ProductHelper
  def class_for_product_date(product, date)
    case product.get_daily_average(date)
    when 0..24
      "product_cell_red"
    when 25..75
      "product_cell_yellow"
    when 76..100
      "product_cell_green"
    else
      ""
    end
  end
end

app/views/products/show.html.haml:

@product.each do |product|
  %td{:class => class_for_product_date(product, date)}
    = product.get_daily_average(date)
0

精彩评论

暂无评论...
验证码 换一张
取 消