Adding methods to native ruby class within rails

hi !

i’d like to add my own method to the ruby string class, do you know how
to do this properly in the rails framework?

itkin

Michael G. wrote:

Something like this?

“foo”.blarg
NoMethodError: undefined method `blarg’ for “foo”:String
from (irb):6
from :0

class String
def blarg
“blarg”
end
end
=> nil

“foo”.blarg
=> “blarg”

yes excactly, but where to place this code in the framework ?

Something like this?

“foo”.blarg
NoMethodError: undefined method `blarg’ for “foo”:String
from (irb):6
from :0

class String
def blarg
“blarg”
end
end
=> nil

“foo”.blarg
=> “blarg”

Michael G. wrote:

Ahh, I understand your question.

I have a private plugin I made for this sort of thing. Just look up
how to make a very simple plug-in, and you’ll be set. If you do that,
you can also maintain it and use it easily in other projects.

–Michael

thanks works great, here is a nice tuto to create its own plugins :
http://railsforum.com/viewtopic.php?id=682

Ahh, I understand your question.

I have a private plugin I made for this sort of thing. Just look up
how to make a very simple plug-in, and you’ll be set. If you do that,
you can also maintain it and use it easily in other projects.

–Michael

I’d place it in an initializer.

Tiago M.

I place the following in MyApp/lib/time_extensions.rb

class Time
def beginning_of_hour
self-(self.min).minutes-self.sec
end
def end_of_hour
self.beginning_of_hour + 1.hour - 1.second
end
def beginning_of_minute
self-self.sec
end
def end_of_minute
self.beginning_of_minute + 1.minute - 1.second
end
def beginning_of(secs=5.minutes)
return self if secs >= 1.day/2
secs_today = self - self.beginning_of_day
periods_today = (secs_today/secs).floor
self.beginning_of_day + periods_today * secs
end
def end_of(secs=5.minutes)
return self if secs >= 1.day/2
beginning_of(secs) + secs - 1.second
end
end

On Jul 12, 11:19 am, nico Itkin [email protected]

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs