Sha256: 525b768a9cfc21ca699e267ba2262303e6ae396c7f00b9557914c3674e67f98d

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

module ByStar
  module ActiveRecord
    extend ActiveSupport::Concern

    module ClassMethods
      include ::ByStar::Base

      # Returns all records between a given start and finish time.
      #
      # Currently only supports Time objects.
      def between_times_query(start, finish, options={})
        start_field = by_star_start_field(options)
        end_field = by_star_end_field(options)

        scope = by_star_scope(options)
        scope = if options[:strict] || start_field == end_field
          scope.where("#{start_field} >= ? AND #{end_field} <= ?", start, finish)
        else
          scope.where("#{end_field} > ? AND #{start_field} < ?", start, finish)
        end
        scope = scope.order(options[:order]) if options[:order]
        scope
      end

      def between(*args)
        ActiveSupport::Deprecation.warn 'ByStar `between` method will be removed in v3.0.0. Please use `between_times`'
        between_times(*args)
      end

      protected

      def by_star_default_field
        "#{self.table_name}.created_at"
      end

      def before_query(time, options={})
        field = by_star_start_field(options)
        by_star_scope(options).where("#{field} <= ?", time)
      end

      def after_query(time, options={})
        field = by_star_start_field(options)
        by_star_scope(options).where("#{field} >= ?", time)
      end
    end

    def previous(options={})
      field = self.class.by_star_start_field
      value = self.send(field.split(".").last)
      self.class.by_star_scope(options).where("#{field} < ?", value).reorder("#{field} DESC").first
    end

    def next(options={})
      field = self.class.by_star_start_field
      value = self.send(field.split(".").last)
      self.class.by_star_scope(options).where("#{field} > ?", value).reorder("#{field} ASC").first
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
by_star-2.2.0 lib/by_star/orm/active_record/by_star.rb