Rails scope returns all(ActiveRecord::Relation) instead of nil.
So that I can use method chain when condition is nil.
class MyClass < ApplicationRecord
scope :my_filter, ->(condition) { where(condition: condition) if condition.present? }
end
MyClass.where(foo: 'foo').my_filter(condition).order(:date)
I want to implement similar functionality in Sequel, but this code doesn't work well because all in Sequel returns an Array. How can I write a functionality in Sequel similar to Rails scope?
class MyClass < Sequel::Model
dataset_module do
def my_filter(condition)
return all if condition.nil?
where(condition: condition)
end
end
end
Since
wherereturns aDatasetI am assuming you would also like "all" to return the same object.As you have identified
allwill return anArray; however you can retrieve theDatasetby using eithercloneorselfSo we can just change your implementation to:
Working Example: https://replit.com/@engineersmnky/SequelGemRailsScope#main.rb
Additional Info:
I chose
clonebecause most query methods utilize this method (similar tospawninActiveRecord).Dataset#clonelooks like thisclone's method signature shortcuts execution if no condition is passed and simply returnsself.As stated in the comments
However the comments do also state
So you could choose to just use
return selfinstead.**I implemented both options in my Example above to show their identical functionality plus that method signature is pretty interesting