Skip to content

Instantly share code, notes, and snippets.

@shouichi
Created August 25, 2010 16:54
Show Gist options
  • Save shouichi/549846 to your computer and use it in GitHub Desktop.
Save shouichi/549846 to your computer and use it in GitHub Desktop.
#
# This module is a collection of named_scope for time column.
# Requires MySQL to work because of usage of MySQL functions.
# But you can easly replace that part to work with another databases.
#
# Example
#
# class Article < ActiveRecord::Base
# include TimeScopes[:created_at]
# end
#
# Article.year(2010).month(8) # Gives you all articles created at 2010-08.
# Article.day_of_week(:monday) # Gives you all articles created at Monday.
#
module TimeScopes
def self.[](column)
Module.new do
(class << self; self; end).send(:define_method, :included) do |base|
base.class_eval do
named_scope :year, lambda { |year|
{ :conditions => ["YEAR(#{column}) = ?", year] } unless year.blank?
}
named_scope :month, lambda { |month|
{ :conditions => ["MONTH(#{column}) = ?", month] } unless month.blank?
}
named_scope :day, lambda { |day|
{ :conditions => ["DAY(#{column}) = ?", day] } unless day.blank?
}
named_scope :day_of_week, lambda { |day_of_week|
day_of_week = %w(:sunday :monday :tuesday :wednesday :thursday :friday :saturday).index(day_of_week)
{ :conditions => ["DAYOFWEEK(#{column}) = ?", day_of_week] } unless day_of_week.nil?
}
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment