- write a 'utility' class which is just a bucket of useful methods - not very elegant and ugly too use.
- extend the built-in Date class and add your own methods - not very convenient because you have to remember too use the class 'MyDate' everywhere
What Ruby lets you do is simply add your own methods to existing classes! This is exactly what's needed.
To do this in rails, simple create a new file in your 'lib' directory called date_extension.rb and put the following code in it.
class Date
def first_of_month
return Date.new(self.year, self.month, 1)
end
end
To get Rails to load this extra method, you need to add the following line to your 'config/environment.rb' file.
require 'date_extension.rb'
To get Rails to load this extra method, you need to add the following line to your 'config/environment.rb' file.
require 'date_extension.rb'
Thats it! You'll need to restart Rails to see the change, but then you can use the new method anywhere in your controllers or templates. For example:
first_of_month = Date.today.first_of_month
You can do the same with String and add your favourite starts_with? or whatever methods.
No comments:
Post a Comment