-
-
Save kivanio/35c7aeb6dda1427e5c90 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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