Skip to content

Instantly share code, notes, and snippets.

@acuppy
Last active December 20, 2015 02:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save acuppy/6054608 to your computer and use it in GitHub Desktop.
Save acuppy/6054608 to your computer and use it in GitHub Desktop.
ActiveRecord Range Scopes => ( between, created_between, updated_between, since, created_since, updated_since, before, created_before, updated_before )
module RangeScopes
extend ActiveSupport::Concern
module ClassMethods
# Order.between(1..5) => pulls all orders who's ids are between 1 and 4
# Order.between(:customer_id, 1..4) => pulls all orders who's orders.customer_id is between 1 and 4
def between(*args)
column = args.first.is_a?(Symbol) ? args.shift : :id
range = args.first
where(column, range)
end
# Order.created_between(1.day.ago..Time.now) => pulls all orders where the created_at is between the range
def created_between(range)
between(:created_at, range)
end
# Order.since(1) => pulls all orders where the id is greater than
# Order.since(:customer_id, 1) => pulls all orders where the provided column id is greater than
def since(*args)
column = args.first.is_a?(Symbol) ? args.shift : :id
where("#{column.to_s} > ?", args.first)
end
# Order.created_since(1.day.ago) => pulls all orders where it was created after 1.day.ago
def created_since(datetime)
since(:created_at, datetime)
end
# Order.updated_since(1.day.ago) => pulls all orders where it was updated after 1.day.ago
def updated_since(datetime)
since(:updated_at, datetime)
end
# Order.before(5) => pulls all orders where the id is less than
# Order.before(:customer_id, 5) => pulls all orders where the provided column id is less than
def before(*args)
column = args.first.is_a?(Symbol) ? args.shift : :id
where("#{column.to_s} < ?", args.first)
end
# Order.created_before(1.days.ago) => pulls all orders where the order was created before
def created_before(datetime)
before(:created_at, datetime)
end
# Order.updated_before(1.days.ago) => pulls all orders where the order was updated before
def updated_before(datetime)
before(:updated_at, datetime)
end
end
end
# Apply to all ActiveRecord::Base models
ActiveRecord::Base.send :include, RangeScopes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment