Class: Metka::Model
- Inherits:
-
Module
- Object
- Module
- Metka::Model
- Defined in:
- lib/metka/model.rb
Instance Method Summary collapse
- #included(base) ⇒ Object
-
#initialize(columns:, **options) ⇒ Model
constructor
A new instance of Model.
Constructor Details
#initialize(columns:, **options) ⇒ Model
Returns a new instance of Model.
17 18 19 20 |
# File 'lib/metka/model.rb', line 17 def initialize(columns:, **) @columns = columns.dup.freeze @options = .dup.freeze end |
Instance Method Details
#included(base) ⇒ Object
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/metka/model.rb', line 22 def included(base) columns = @columns parser = ->() { @options[:parser] ? @options[:parser].call() : Metka.config.parser.instance.call() } # @param model [ActiveRecord::Base] model on which to execute search # @param tags [Object] list of tags, representation depends on parser used # @param options [Hash] options # @option :join_operator [Metka::AND, Metka::OR] # @option :on [Array<String>] list of column names to include in query # @returns ViewPost::ActiveRecord_Relation tagged_with_lambda = ->(model, , **) { cols = .delete(:on) parsed_tag_list = parser.call() return model if parsed_tag_list.empty? request = ::Metka::QueryBuilder.new.call(model, cols, parsed_tag_list, ) model.where(request) } base.class_eval do columns.each do |column| scope "with_all_#{column}", ->() { tagged_with(, on: [column]) } scope "with_any_#{column}", ->() { tagged_with(, on: [column], any: true) } scope "without_all_#{column}", ->() { tagged_with(, on: [column], exclude: true) } scope "without_any_#{column}", ->() { tagged_with(, on: [column], any: true, exclude: true) } end unless respond_to?(:tagged_with) scope :tagged_with, ->( = '', = {}) { [:join_operator] ||= ::Metka::OR = {any: false}.merge() [:on] ||= columns tagged_with_lambda.call(self, , **) } end end base.define_singleton_method :metka_cloud do |*columns| return [] if columns.blank? prepared_unnest = columns.map { |column| "#{table_name}.#{column}" }.join(' || ') subquery = all.select("UNNEST(#{prepared_unnest}) AS tag_name") unscoped.from(subquery).group(:tag_name).pluck(:tag_name, Arel.sql('COUNT(*) AS taggings_count')) end columns.each do |column| base.define_method(column.singularize + '_list=') do |v| write_attribute(column, parser.call(v).to_a) write_attribute(column, nil) if send(column).empty? end base.define_method(column.singularize + '_list') do parser.call(send(column)) end base.define_singleton_method :"#{column.singularize}_cloud" do metka_cloud(column) end end end |