On Tue, Sep 21, 2021 at 10:44 AM [email protected] < [email protected]> wrote:
> Hi Jeremy, > > I'm working on a plugin that is similar to the subset_conditions plugin, > but is for the `order` method. Basing off the subset_conditions plugin has > worked well so far, but I'm not sure if there is a mechanism for capturing > and preserving a block passed `order`, as there is for `subset` (by using > the `filter_expr` method). > > Here's my working plugin (also in Gist if it's Google Groups decides to > eat the formatting): > https://gist.github.com/adam12/4fc21b8a3a96df5bcdb1082510676bda > > module Sequel > module Plugins > module OrderConditions > def self.apply(model, &block) > model.instance_exec do > @dataset_module_class = Class.new(@dataset_module_class) do > include DatasetModuleMethods > end > end > end > > module DatasetModuleMethods > # Also create a method that returns the order > def order(name, *args, &block) > super > cond = args > cond = cond.first if cond.size == 1 > define_method(:"#{name}_order"){cond} if block.nil? > super define_method(:"#{name}_order") do args = args.dup virtual_row_columns(args, block) args end > end > end > end > end > end > > For the line with `define_method`, I'm skipping this if there is a block > provided, as I don't see a nice way of capturing this. I don't personally > use a block for `order`, but I wonder if you know of a method to preserve > the block, perhaps one that generates an SQL::OrderedExpression? I looked > through the docs and source and didn't come across one. I'm presuming the > block will be of no use for this purpose (using the order in another model) > but I want to explore all avenues. > > My goal is to be able to do something like this: > > Widget.dataset_module { order :by_id, Sequel.asc(:id) } > Catalog.one_to_many :widgets, order: Widget.by_id_order > I think the above code should work for you. It will have by_id_order return an array instead of a single argument, but I don't think that should cause a problem, as it makes things more consistent. You could always extend it to support a single argument if a block is not provided, or do other optimizations if a block is not provided. Thanks, Jeremy -- You received this message because you are subscribed to the Google Groups "sequel-talk" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/sequel-talk/CADGZSScW4qNtU_-F52PnggZr0eo2-WK0%3Dk9PdWY-mhPCcdw%3D-Q%40mail.gmail.com.
