views:

53

answers:

3

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?

+1  A: 

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
phaedryx
And a little shorter with: `self.month + self.strftime("/%y")`
Brian
+2  A: 

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)
John Topley
`date.strftime("%m/%y")` != `self.strftime("%m").to_i.to_s + self.strftime("/%y")` it doesn't remove the leading zero
jigfox
Good catch, I've edited my answer.
John Topley
I did that, but when I went to in-place-editing I created another helper... def editable(this_model, this_element, args={}) classes = "editable".join(args[:class]," ") s = args[:format] ? this_model.send(this_element).send(args[:format]) : this_model.send(this_element) "<span class='#{classes}' id='seeker-#{this_model.id}-#{this_element}'>#{s}</span> " endused like this in haml...= editable(experience, "date", :format=>:as_month_and_year, :class=>"arial10")and while I could figure out how to do this with a class method, I couldn't figure out how to use the helper method.
Paul
Please post that as a separate question, because it's really not related to this one.
John Topley
fair enough, will do
Paul
+1  A: 

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
jigfox
It's elegant, but extending three built-in Ruby classes for what is a simple view concern is IMHO overkill in this situation.
John Topley
it's the railsway: http://github.com/rails/rails/tree/master/activesupport/lib/active_support/core_ext/
jigfox
I'm fully aware that the ActiveSupport module provides all sorts of useful extensions to Ruby's classes, but that's because Rails is a *framework*. It also provides the view helper mechanism for exactly this type of problem.
John Topley
What is the down vote for? I really would appreciate a comment. It's funny to get an accepted answer down voted, and I'm really interested why?
jigfox