Sha256: c680b8b012e87f17c6a73a38ff59706861584b0cdafb7e908648ca22c938db8e

Contents?: true

Size: 1.66 KB

Versions: 9

Compression:

Stored size: 1.66 KB

Contents

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

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

      def apply
        return unless @field_name =~ @cropped_field_regex

        model.class_eval <<-RUBY, __FILE__, __LINE__ + 1
          #{before_scopes}
          #{after_scopes}
          #{between_scopes}
          #{boolean_scopes}
        RUBY
      end

    private

      def before_scopes
        <<-RUBY
          scope "#{cropped_field}_before", lambda { |time| where('#{quoted_field} < ?', time) }
          scope "#{cropped_field}_before_or_at", lambda { |time| where('#{quoted_field} <= ?', time) }
          scope "#{cropped_field}_before#{@now_suffix}", lambda { where('#{quoted_field} < ?', #{@now}) }
        RUBY
      end

      def after_scopes
        <<-RUBY
          scope "#{cropped_field}_after", lambda { |time| where('#{quoted_field} > ?', time) }
          scope "#{cropped_field}_after_or_at", lambda { |time| where('#{quoted_field} >= ?', time) }
          scope "#{cropped_field}_after#{@now_suffix}", lambda { where('#{quoted_field} > ?', #{@now}) }
        RUBY
      end

      def between_scopes
        <<-RUBY
          scope "#{cropped_field}_between", lambda { |range| where("#{@field_name}" => range) }
        RUBY
      end

      def boolean_scopes
        <<-RUBY
          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}) }
        RUBY
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
microscope-0.5.7 lib/microscope/scope/datetime_scope.rb
microscope-0.5.6.1 lib/microscope/scope/datetime_scope.rb
microscope-0.5.6 lib/microscope/scope/datetime_scope.rb
microscope-0.5.5 lib/microscope/scope/datetime_scope.rb
microscope-0.5.4 lib/microscope/scope/datetime_scope.rb
microscope-0.5.3 lib/microscope/scope/datetime_scope.rb
microscope-0.5.2 lib/microscope/scope/datetime_scope.rb
microscope-0.5.1 lib/microscope/scope/datetime_scope.rb
microscope-0.5 lib/microscope/scope/datetime_scope.rb