Search code examples
ruby-on-railsrubytimerform-helpersrecipe

Ruby on Rails time helper


I'm working on my first Rails Application. I am a little stuck with the time. I'm working on a recipe application. I need to add two fields.

  • Preparation Time
  • Cook Time

Out of the two, i would like to add the two fields to come up with the Total Time needed to prepare the meal.

I approached it the wrong way which doesn't have logic :(. Basically i have two fields and i used f.select to select predefined times. But the problem i have with that approach is that when adding the two, it ignores the Gregorian format e.g 40 minutes + 50 mins will become 90 Min instead of 1hour 30.

I would appreciate any help from the community.


Solution

  • A quick example:

    prep_time = 40.minutes
    cook_time = 50.minutes
    
    total_time = prep_time + cook_time
    formatted_total_time = Time.at(total_time).gmtime.strftime('%I:%M')
    
    # outputs 01:30 which is HOURS:MINUTES format
    

    If you wanted 90 minutes instead:

    formatted_total_time = total_time / 60
    
    # outputs 90
    

    Update:

    Put this in the helper file associated with whatever view you are using this in (i.e. app/helpers/recipes_helper.rb)

    module RecipesHelper
    
      def convert_to_gregorian_time(prep_time, cook_time)
        # returns as 90 mins instead of 1hr30mins
        return (prep_time + cook_time) / 60
      end
    
    end
    

    Then you'd just call it in your view (i.e. app/views/recipes/show.html.haml like:

    # Note: this is HAML code... but ERB should be similar
    
    %p.cooking_time
      = convert_to_gregorian_time(@recipe.prep_time, @recipe.cook_time)
    

    If you are storing the times in the database as integers (which you SHOULD be doing), then you can do this:

    %p.cooking_time
      = convert_to_gregorian_time(@recipe.prep_time.minutes, @recipe.cook_time.minutes)
    

    where @recipe.prep_time is an integer with a value of 40 and @recipe.cook_time is an integer with a value of 50

    and your database schema would look something like:

    # == Schema Information
    #
    # Table name: recipes
    #
    #  id                 :integer         not null, primary key
    #  prep_time          :integer
    #  cook_time          :integer
    #  # other fields in the model...