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

621 Views Asked by At

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
3

There are 3 best solutions below

1
On BEST ANSWER

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.

0
On

I think it is to do with the property :peep_timestamp, Time. As (rather unintuitively) Time includes a date. I think you need to create a method within Peep that changes what is saved for this property so that it doesn't make reference to the date.

1
On

You're not using the time_stamp method, you're directly calling #peep_timestamp.

You can do something like the following to display it as you want.

<%= time_stamp(peep.peep_timestamp) %>