Forum: Ruby on Rails Rails related Ruby question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
8dad1ec4d769734583f45fbbee5cd009?d=identicon&s=25 Jeff Pritchard (jeffpritchard)
on 2009-02-28 21:51
I'm doing an app that has a very frequent need to compare dates.  My
code is littered with things like:

return if foo.date < 10.days.ago

Each and every time I do one of these I have to stop and think it
through to get the sense of the comparison right.  "Let's see, recent
dates are bigger than older dates, so if I want this to happen when the
date on the left is longer ago than the date on the right..."  You get
the idea.

I want to open up the date class and add a couple of methods to it like
"is_more_recent_than" and "is_longer_ago_than", so I don't have to think
about it anymore and so my code is more readable.

There are two things I'm not sure of with this, when I define the
method, what does the method def syntax look like?  Maybe:

def is_more_recent_than(right_hand_value)
   self > right_hand_value   # just had to think about this for the last
time!
end

and the other thing is, where can I put this such that it will be
available from controllers, and from models and from views?  do I have
to put it in more than one place to have it be automatically available
(without doing an include when I want to use it) everywhere?  Maybe it
needs to be in one of my Rails files instead of in my app project?

thanks,
jp
A91bd6cef23eb3516245a092e196c4da?d=identicon&s=25 Maurício Linhares (mauricio)
on 2009-02-28 23:06
(Received via mailing list)
A simple and clean way (and also the preffered way of doing this) is
by a Rails plugin.

Create a folder under vendor/plugins, maybe "date_extensions", create
an "init.rb" file. Your init.rb would look like this:

Date.class_eval do

  def is_older_than( other_date )
    self < other_date
  end

end

And so on, adding the other methods you want. For more about ruby
method definition, read the metaprogramming chapter from ->
http://oreilly.com/catalog/9780596516178/toc.html

-
Maurício Linhares
http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
(en)



On Sat, Feb 28, 2009 at 5:51 PM, Jeff Pritchard
8dad1ec4d769734583f45fbbee5cd009?d=identicon&s=25 Jeff Pritchard (jeffpritchard)
on 2009-03-01 00:05
Maurício Linhares wrote:
> A simple and clean way (and also the preffered way of doing this) is
> by a Rails plugin.
>
> Create a folder under vendor/plugins, maybe "date_extensions", create
...
> Maur�cio Linhares
> http://alinhavado.wordpress.com/ (pt-br) | http://blog.codevader.com/
> (en)

Thanks Mauricio,
I had no idea it was that simple to make a plugin!

thanks,
jp
This topic is locked and can not be replied to.