rubysinatradatetime-formatirbrackup

In Ruby/Sinatra Time.now formatting is working in IRB but not in rackup/local


I created this method for my class

def time_stamp(time)
  time.strftime("%I:%M%p") 
end

in IRB when I don't require, and enter the method and put

time_stamp(Time.now)

it returns: "07:57PM" which is what I want

in Sinatra, though I have created a new peep object:

@peep = Peep.new(:peep_timestamp => time_stamp(Time.now))

but when I go to rackup and look at my local it still has the time unformatted: 2015-01-17 19:15:23 +0000 (for example). I would like it to say "07:57PM" or whatever the current time is when I create my Peep object.

Even if I type

@peep6 = Peep.new(:peep_timestamp => "8:34PM")

it returns:

<Peep @id=nil @message=nil @peep_timestamp=2015-01-17 20:34:00 +0000>

My whole Peep class looks like:

  class Peep

  include DataMapper::Resource

  property :id,     Serial 
  property :message, Text
  property :peep_timestamp, Time
  property :username, String

  def time_stamp(time)
    time.strftime("%I:%M%p") 
  end

end

Solution

  • Thanks for sharing your class, the issue is that Peep is expecting a Time object but you're sending it a formatted string.

    It be better practice to do this:

      class Peep
    
      include DataMapper::Resource
      property :peep_timestamp, Time
    
      def format_time
        self.peep_timestamp.strftime("%I:%M%p") 
      end
    
    end
    

    now you can still instantiate the class with:

    @peep = Peep.new(peep_timestamp: Time.now)
    

    and in your view call your helper method like so:

    <%= @peep.format_time %>
    

    You want your object to have a Time object, but for view purposes you can coerce it into any format you want, but you'll always have access to the full Time object should you need to change something in your view.