Model methods


#1

Hello everyone,

In my model, I have

def leave_at_formatted
	leave_at.strftime("%I:%M %p")
end

I was wondering if there were any way to define to_s for leave_at in
order
to get the same result?

Thanks!


#2

I’m afraid I may have been unclear - in the code below, leave_at is an
attribute of the model

Hello everyone,

In my model, I have

def leave_at_formatted
	leave_at.strftime("%I:%M %p")
end

I was wondering if there were any way to define to_s for leave_at in
order
to get the same result?

Thanks!


Rails mailing list
removed_email_address@domain.invalid
http://lists.rubyonrails.org/mailman/listinfo/rails


#3

On Sat, 2006-05-20 at 17:06 -1000, Daniel H. wrote:

end

I was wondering if there were any way to define to_s for leave_at in order
to get the same result?


I’m gathering that ‘leave_at’ is actually a column in your db and you
don’t want to have to convert in/out when you use it.

I have the following in my ‘environment.rb’

ActiveSupport::CoreExtensions::date::Conversions::DATE_FORMATS.merge!(
:default => ‘%m/%d/%Y’,
:date_time12 => “%m/%d/%Y %I:%M%p”,
:date_time24 => “%m/%d/%Y %H:%M”)

but that becomes a default for all usage in my application - though this
is Date Class, I am sure that you can do similarly for Time Class.

Craig


#4

On Sat, May 20, 2006 at 05:06:40PM -1000, Daniel H. wrote:
} I’m afraid I may have been unclear - in the code below, leave_at is an
} attribute of the model
}
} >>
} Hello everyone,
}
} In my model, I have
}
} def leave_at_formatted
} leave_at.strftime("%I:%M %p")
} end
}
} I was wondering if there were any way to define to_s for leave_at in
order
} to get the same result?

I don’t recommend it, but it is possible:

module LeaveAtFormat
def to_s
strftime("%I:%M %p")
end
end

class WhateverModel
def leave_at
val = self[:leave_at]
class << val
include LeaveAtFormat
end
return val
end
end

You extend the individual object to define #to_s the way you want as you
are returning it.

} Thanks!
–Greg


#5

Ah, didn’t know you could do that, thanks!


#6

I was afraid it’d be something like that… Thanks!