Date string conversion
I have a date string: "2009-10-12". I would like to write a method that takes this as a parameter and returns the three letter day of the week (in this case "mon"). I wrote this:
def date_to_day_of_week(date)
d = Date.parse(date).strftime("%a").downcase!
return d
end
When I call this from the script / console, it works as expected. However, when I call this from my application, I get a lot of different errors depending on what I am doing. The main problems are that either date_to_day_of_week
the method is undefined, or if I move the content of the method (i.e. day = Date.parse(date).strftime("%a").downcase!
inline, then I get private method gsub! called for Mon, 12 Oct 2009:Date
). I just think I start to understand Ruby and Rails and then I go back to the beginning!
Can anyone help with this?
Woof
source to share
Where is this code located? If, for example, this is in a model called by the controller, you can go with:
def self.date_to_day_of_week(date)
d = Date.parse(date).strftime("%a").downcase!
return d
end
And call it in your controller with:
def index
# ...
@date = Model.date_to_day_of_week("2009-12-30")
end
source to share
If you get an "undefined" error, it means that this method is not available from the moment it was called.
If you are trying to call it from a helper, you need to put this method in your ApplicationHelper, not in ApplicationController. If you also want it to be accessible from your controllers, inject the following into your ApplicationController:
helper_method :date_to_day_of_week
source to share
try it
def date_to_day_of_week(date)
Date.parse(date).strftime("%a").downcase
end
Ruby returns the last value evaluated in the method, so you don't need to specifically return anything. Same! in lower case! just changes the value of the string it was called on, instead of returning the value as you would expect.
source to share