views:

59

answers:

2

I have two models, BusinessHour and StaffHour that both inherit from Hour.

In the BusinessHour and StaffHour models I do a 'find' to retrieve requested hours. After that I need to format each time to a specific format, which I have a method for. I'm trying to figure out where to put that method. It sort of seems like it would go in a Helper in which case I would need to call the it from the both the BusinessHour and StaffHour controllers AFTER they call the model to retrieve the data.

Otherwise I can put the formatting method in the Hour model, and call it right from within the BusinessHour and StaffHour models since they both inherit from Hour.

What's the recommended way?

Here's the method:

  def self.format_hours_for_display(hours)
    hours_for_day = Hash.new("")
    hours.each do |h|
      h.start_time  = format_time(h.start_time)
      h.stop_time   = format_time(h.stop_time)
      hours_for_day[h.day] = h
    end  
    hours_for_day
  end
+4  A: 

You can define custom formats of to_s for dates and times. Create a .rb file in config/initializers with something such as the following:

formats = {:short_full_year => '%m/%d/%Y', :short_datetime => '%m/%d/%Y %I:%M%p'}

Date::DATE_FORMATS.update(formats)
Time::DATE_FORMATS.update(formats)

Then you can call to_s with any of the formats you've created. Like so:

time = Time.now
time.to_s(:short_full_year)
Jared
Hey, that's pretty slick! Thanks, I got that working, and I'll use it.I'm still curious where it's recommended I put this method I have that takes the array of results from the 'find', loops through it, and reformats each of the dates.I'm adding the method to the bottom of the original post.
99miles
I don't think you're thinking about this the way you should be. With what I've given you above, you shouldn't need any other methods.If you follow MVC strictly, you shouldn't be doing any formatting in your controllers or models. That sort of logic needs to go either into a view or a helper. Just do your model find and save it to an instance variable. Then call to_s(:my_format) in the views/helpers where needed.
Jared
A: 

If you've defined your custom time format as Jared says, your format_hours_for_display method is merely grouping hours by day. Rails has a nice group_by method that you could probably use, something like this:

hours.group_by(&:day).each do |day, h|
  puts h.start_time.to_s(:custom_format)
  puts h.stop_time.to_s(:custom_format)
end
Ben Marini