开发者

Date and Time in ROR

开发者 https://www.devze.com 2023-01-08 08:58 出处:网络
In my app I want the time/date to display as Month/Year (e.g. 7/10). The problem is sometimes I get class Date and sometimes class Time so I wind up with the following code in the application controll

In my app I want the time/date to display as Month/Year (e.g. 7/10). The problem is sometimes I get class Date and sometimes class Time so I wind up with the following code in the application controller ...

class Date
  def as_month_and_year
    self.strftime("%m").to_i.to_s + self.strftime(开发者_运维百科"/%y")
  end
end

class Time
  def as_month_and_year
    self.strftime("%m").to_i.to_s + self.strftime("/%y")
  end
end

what's the best way to DRY this up?


I would create a view helper method that accepts a Date or Time instance and formats appropriately. No need to re-open the Date and Time classes. This sort of thing is exactly what the view helper modules are for.

def as_month_and_year(date)
  date.strftime("%m").to_i.to_s + self.strftime("/%y") 
end

Then in your views you can just use:

<%= as_month_and_year(@object.created_at)


IMHO the more elegant solution:

module DateTimeExtensions
  def as_months_and_year
    self.strftime('%m/%y').sub(/^0/,'')
  end
  [Time, Date, DateTime].each{ |o| o.send :include, self }
end


Maybe something like this?

module DateTimeExtensions
  def as_month_and_year
    self.strftime("%m").to_i.to_s + self.strftime("/%y")
  end
end

class Date; include DateTimeExtensions; end
class Time; include DateTimeExtensions; end
class DateTime; include DateTimeExtensions; end
0

精彩评论

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