Sha256: 236469d65ed12c0247cb794b0b368b64551ffe98fc14633581d9095e13746956

Contents?: true

Size: 1.46 KB

Versions: 2

Compression:

Stored size: 1.46 KB

Contents

module Telescope
  module Mixin
    extend ActiveSupport::Concern

    included do
      define_telescope_scopes
    end

    module ClassMethods
      def define_telescope_scopes
        model_columns = self.columns.dup

        boolean_fields = model_columns.select { |c| c.type == :boolean }.map(&:name)
        boolean_fields.each do |field|
          class_eval <<-RUBY, __FILE__, __LINE__ + 1
            scope field, lambda { where(field => true) }
            scope "not_#{field}", lambda { where(field => false) }
          RUBY
        end

        datetime_fields = model_columns.select { |c| c.type == :datetime }.map(&:name)
        datetime_fields.each do |field|
          cropped_field = field.gsub(/_at$/, '')
          class_eval <<-RUBY, __FILE__, __LINE__ + 1
            scope "#{cropped_field}_before", lambda { |time| where(["#{field} < ?", time]) }
            scope "#{cropped_field}_before_or_at", lambda { |time| where(["#{field} <= ?", time]) }
            scope "#{cropped_field}_before_now", lambda { where(["#{field} < ?", Time.now]) }

            scope "#{cropped_field}_after", lambda { |time| where(["#{field} > ?", time]) }
            scope "#{cropped_field}_after_or_at", lambda { |time| where(["#{field} >= ?", time]) }
            scope "#{cropped_field}_after_now", lambda { where(["#{field} > ?", Time.now]) }

            scope "#{cropped_field}_between", lambda { |range| where(field => range) }
          RUBY
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
telescope-0.0.2 lib/telescope/mixin.rb
telescope-0.0.1 lib/telescope/mixin.rb