Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sikachu/139946 to your computer and use it in GitHub Desktop.
Save sikachu/139946 to your computer and use it in GitHub Desktop.
Provide an extension for String's % method to call time#strftime if given argument is a Time object
# string_format_with_strftime_extension.rb
#
# Provide extension for String's % method to call Time%strftime when given argument
# is a Time object. So we can do <tt>"%d/%m/%Y" % Time.now</tt> and get the same
# result as <tt>Time.now.strftime "%d/%m/%Y"</tt>
#
# Put this file in #{RAILS_ROOT}/config/initializers so it will be automatically loaded.
class String
alias_method :format_without_strftime_extension, :%
# Format -- Apply formatting using <tt>str</tt> as a format specification and
# returns the result of applying it to <tt>arg</tt>. If the format specification
# contains more than one substitution, then <tt>arg</tt> must be an Array containing
# the values to be substituted.
#
# "%05d" % 123 #=> "00123"
# "%-5s: %08x" % [ "ID", self.id ] #=> "ID : 200e14d6"
#
# However, if the <tt>arg</tt> is an instance of Time, then Time#strftime will be
# called on <tt>arg</tt> by using <tt>str</tt> as an argument instead. This action
# can be override by putting that Time instance into Array.
#
# "%d/%m/%y" % Time.now.utc #=> "03/07/09"
# "Current timestamp is: %s" % Time.now.utc #=> "Current timestamp is: 1246577322"
# "Today: %s" % [Time.now.utc] #=> "Today: Fri Jul 03 06:29:19 UTC 2009"
def %(arg)
if arg.is_a? Array or !arg.is_a? Time
format_without_strftime_extension(arg)
else
arg.strftime(self)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment