views:

388

answers:

6

Hi,

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 lettered 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 script/console, it works as expected. However, when I call this from within my app I get a variety of different errors depending on what I do. The main problems are that either date_to_day_of_week is an undefined method, or if I move the contents 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'm starting to understand Ruby and Rails and then I get thrown back to the start!

Can anyone help with this?

Gav

A: 

Look at ActiveSupport::CoreExtensions::Date::Conversions. You can define your own DATE_FORMATS and output it with "to_formatted_s". I believe what you want for an abbreviated month is "%b"

Todd R
A: 

If you're getting an "undefined method" error, that means this method is inaccessible from the point it's being called.

If you're trying to call it from a helper, you need to place the method in your ApplicationHelper, not your ApplicationController. If you also want it to be accessible from your controllers, then put the following in your ApplicationController:

helper_method :date_to_day_of_week
insane.dreamer
"If you're trying to call it from a helper" should probably be "If you're trying to call it from a view"
mikej
yes, that's what I meant; was typing too fast :-)
insane.dreamer
A: 

say dt = Time.now() dt.strftime("%a") gives you the day

philipth
A: 

try this

def date_to_day_of_week(date)
  Date.parse(date).strftime("%a").downcase
end

Ruby returns the last value evaluated in a method, so you do not need to specifically return anything. Also, the ! in downcase! simply changes the value of the string it was called on rather than returning the value as you're expecting.

mculp
A: 

Where is this code located? If, for instance, it's in a model called by a controller you may want to 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
Orlando
A: 

Did you try

day = Date.parse(date).strftime("%a").to_s.downcase

The date methods do work slightly differently within rails versus ruby, because of ActiveSupport

Browsera