Sha256: 7a5e22fc45622da065665aac0e013cc5e409c5fa523ae008bb086a483bd7426d

Contents?: true

Size: 1.75 KB

Versions: 2

Compression:

Stored size: 1.75 KB

Contents

module Microscope
  class Scope
    class DatetimeScope < Scope
      def initialize(*args)
        super

        @now = 'Time.now'
        @now_suffix = '_now'
        @specific_suffix = '_at'
        @cropped_field_regex = /_at$/
        @formatted_time = 'time'
      end

      def apply
        model.class_eval(apply_scopes) if @field_name =~ @cropped_field_regex
      end

    private

      def apply_scopes
        <<-RUBY
          scope "#{cropped_field}_before", lambda { |time| where('#{quoted_field} < ?', #{@formatted_time}) }
          scope "#{cropped_field}_before_or#{@specific_suffix}", lambda { |time| where('#{quoted_field} <= ?', #{@formatted_time}) }
          scope "#{cropped_field}_before#{@now_suffix}", lambda { where('#{quoted_field} < ?', #{@now}) }
          scope "#{cropped_field}_before_or#{@now_suffix}", lambda { where('#{quoted_field} <= ?', #{@now}) }

          scope "#{cropped_field}_after", lambda { |time| where('#{quoted_field} > ?', #{@formatted_time}) }
          scope "#{cropped_field}_after_or#{@specific_suffix}", lambda { |time| where('#{quoted_field} >= ?', #{@formatted_time}) }
          scope "#{cropped_field}_after#{@now_suffix}", lambda { where('#{quoted_field} > ?', #{@now}) }
          scope "#{cropped_field}_after_or#{@now_suffix}", lambda { where('#{quoted_field} >= ?', #{@now}) }

          scope "#{cropped_field}_between", lambda { |range| where("#{@field_name}" => range) }

          scope "#{cropped_field}", lambda { where('#{quoted_field} IS NOT NULL AND #{quoted_field} <= ?', #{@now}) }
          scope "not_#{cropped_field}", lambda { where('#{quoted_field} IS NULL OR #{quoted_field} > ?', #{@now}) }
          scope "un#{cropped_field}", lambda { not_#{cropped_field} }
        RUBY
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
microscope-1.0.0 lib/microscope/scope/datetime_scope.rb
microscope-0.6.2 lib/microscope/scope/datetime_scope.rb