can_selector.rb 857 B

123456789101112131415161718192021222324252627
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. module CanSelector
  3. extend ActiveSupport::Concern
  4. class_methods do
  5. def selectors(selectors, options = {})
  6. limit = options[:limit] || 10
  7. raise 'no selectors given' if !selectors
  8. query, bind_params, tables = selector2sql(selectors, options)
  9. return [] if !query
  10. ActiveRecord::Base.transaction(requires_new: true) do
  11. objects = distinct.where(query, *bind_params).joins(tables).reorder(options[:order_by])
  12. [objects.count, objects.limit(limit)]
  13. rescue ActiveRecord::StatementInvalid => e
  14. Rails.logger.error e
  15. raise ActiveRecord::Rollback
  16. end
  17. end
  18. def selector2sql(selectors, options = {})
  19. Selector::Sql.new(selector: selectors, options: options, target_class: self).get
  20. end
  21. end
  22. end