In my previous post, I have explained how to extend ActiveRecord::Base. In this post, I will explain how to extend core ruby or rails classes in rails.

Create a file date_extensions.rb in lib folder and add your extension code. Below is the example to extend Date class.

class Date
  MONTH_YEAR_FORMAT = '%b/%Y'

  def month_year
    self.strftime(MONTH_YEAR_FORMAT)
  end

  def self.month_year_to_date month_year
    Date.strptime(month_year, '%b/%Y')
  end
end

Create a rails initializer file application.rb. In the initializer load the date_extensions.rb like require 'date_extensions.rb' Now the rails will load the date_extensions.rb on boot and all the date methods we created will be available for use.

Above date extension has got a method month_year to get only month and year from the date in format %b/%Y' as string. Similary a class method is defined to get date from the month_year string.


[3] pry(main)> today = Date.today
=> Mon, 25 Jul 2016

[4] pry(main)> today.month_year
=> "Jul/2016"

[5] pry(main)> Date.month_year_to_date 'Jul/2016'
=> Fri, 01 Jul 2016