/
by_star.rb
63 lines (50 loc) · 1.39 KB
/
by_star.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
require 'chronic'
require 'by_star/time_ext'
require 'by_star/instance_methods'
require 'by_star/by_direction'
require 'by_star/by_year'
require 'by_star/by_month'
require 'by_star/by_fortnight'
require 'by_star/by_week'
require 'by_star/by_weekend'
require 'by_star/by_day'
module ByStar
def by_star_field(field=nil)
@by_star_field ||= field
@by_star_field || "created_at"
end
include ByDirection
include ByYear
include ByMonth
include ByFortnight
include ByWeek
include ByWeekend
include ByDay
class ParseError < StandardError
end
# Returns all records between a given start and finish time.
#
# Currently only supports Time objects.
def between(start, finish, options={})
field = options[:field] || by_star_field
scope = where("#{field} >= ? AND #{field} <= ?",
start, finish)
scope = scope.order(options[:order]) if options[:order]
scope
end
private
# Used inside the by_* methods to determine what kind of object "time" is.
# These methods take the result of the time_klass method, and call other methods
# using it, such as by_year_Time and by_year_String.
def time_klass(time)
case time
when ActiveSupport::TimeWithZone
Time
else
time.class
end
end
end
ActiveRecord::Base.send :extend, ByStar
ActiveRecord::Relation.send :extend, ByStar
ActiveRecord::Base.send :include, ByStar::InstanceMethods