Module: AlgoliaSearch::ClassMethods

Defined in:
lib/algoliasearch-rails.rb

Overview

these are the class methods added when AlgoliaSearch is included

Defined Under Namespace

Modules: AdditionalMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/algoliasearch-rails.rb', line 342

def self.extended(base)
  class <<base
    alias_method :without_auto_index, :algolia_without_auto_index unless method_defined? :without_auto_index
    alias_method :reindex!, :algolia_reindex! unless method_defined? :reindex!
    alias_method :reindex, :algolia_reindex unless method_defined? :reindex
    alias_method :index_objects, :algolia_index_objects unless method_defined? :index_objects
    alias_method :index!, :algolia_index! unless method_defined? :index!
    alias_method :remove_from_index!, :algolia_remove_from_index! unless method_defined? :remove_from_index!
    alias_method :clear_index!, :algolia_clear_index! unless method_defined? :clear_index!
    alias_method :search, :algolia_search unless method_defined? :search
    alias_method :raw_search, :algolia_raw_search unless method_defined? :raw_search
    alias_method :search_facet, :algolia_search_facet unless method_defined? :search_facet
    alias_method :search_for_facet_values, :algolia_search_for_facet_values unless method_defined? :search_for_facet_values
    alias_method :index, :algolia_index unless method_defined? :index
    alias_method :index_name, :algolia_index_name unless method_defined? :index_name
    alias_method :must_reindex?, :algolia_must_reindex? unless method_defined? :must_reindex?
  end

  base.cattr_accessor :algoliasearch_options, :algoliasearch_settings
end

Instance Method Details

#algolia_clear_index!(synchronous = false) ⇒ Object



592
593
594
595
596
597
598
599
600
601
# File 'lib/algoliasearch-rails.rb', line 592

def algolia_clear_index!(synchronous = false)
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    index = algolia_ensure_init(options, settings)
    next if options[:slave] || options[:replica]
    synchronous || options[:synchronous] ? index.clear! : index.clear
    @algolia_indexes[settings] = nil
  end
  nil
end

#algolia_index(name = nil) ⇒ Object



684
685
686
687
688
689
690
691
692
# File 'lib/algoliasearch-rails.rb', line 684

def algolia_index(name = nil)
  if name
    algolia_configurations.each do |o, s|
      return algolia_ensure_init(o, s) if o[:index_name].to_s == name.to_s
    end
    raise ArgumentError.new("Invalid index/replica name: #{name}")
  end
  algolia_ensure_init
end

#algolia_index!(object, synchronous = false) ⇒ Object



549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
# File 'lib/algoliasearch-rails.rb', line 549

def algolia_index!(object, synchronous = false)
  return if algolia_without_auto_index_scope
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    object_id = algolia_object_id_of(object, options)
    index = algolia_ensure_init(options, settings)
    next if options[:slave] || options[:replica]
    if algolia_indexable?(object, options)
      raise ArgumentError.new("Cannot index a record with a blank objectID") if object_id.blank?
      if synchronous || options[:synchronous]
        index.add_object!(settings.get_attributes(object), object_id)
      else
        index.add_object(settings.get_attributes(object), object_id)
      end
    elsif algolia_conditional_index?(options) && !object_id.blank?
      # remove non-indexable objects
      if synchronous || options[:synchronous]
        index.delete_object!(object_id)
      else
        index.delete_object(object_id)
      end
    end
  end
  nil
end

#algolia_index_name(options = nil) ⇒ Object



694
695
696
697
698
699
# File 'lib/algoliasearch-rails.rb', line 694

def algolia_index_name(options = nil)
  options ||= algoliasearch_options
  name = options[:index_name] || model_name.to_s.gsub('::', '_')
  name = "#{name}_#{Rails.env.to_s}" if options[:per_environment]
  name
end

#algolia_index_objects(objects, synchronous = false) ⇒ Object



539
540
541
542
543
544
545
546
547
# File 'lib/algoliasearch-rails.rb', line 539

def algolia_index_objects(objects, synchronous = false)
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    index = algolia_ensure_init(options, settings)
    next if options[:slave] || options[:replica]
    task = index.save_objects(objects.map { |o| settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, options) })
    index.wait_task(task["taskID"]) if synchronous || options[:synchronous]
  end
end

#algolia_must_reindex?(object) ⇒ Boolean

Returns:

  • (Boolean)


701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
# File 'lib/algoliasearch-rails.rb', line 701

def algolia_must_reindex?(object)
  algolia_configurations.each do |options, settings|
    next if options[:slave] || options[:replica]
    return true if algolia_object_id_changed?(object, options)
    settings.get_attribute_names(object).each do |k|
      changed_method = "#{k}_changed?"
      return true if !object.respond_to?(changed_method) || object.send(changed_method)
    end
    [options[:if], options[:unless]].each do |condition|
      case condition
      when nil
      when String, Symbol
        changed_method = "#{condition}_changed?"
        return true if !object.respond_to?(changed_method) || object.send(changed_method)
      else
        # if the :if, :unless condition is a anything else,
        # we have no idea whether we should reindex or not
        # let's always reindex then
        return true
      end
    end
  end
  return false
end

#algolia_raw_search(q, params = {}) ⇒ Object



603
604
605
606
607
608
609
610
611
612
# File 'lib/algoliasearch-rails.rb', line 603

def algolia_raw_search(q, params = {})
  index_name = params.delete(:index) ||
               params.delete('index') ||
               params.delete(:slave) ||
               params.delete('slave') ||
               params.delete(:replica) ||
               params.delete('replica')
  index = algolia_index(index_name)
  index.search(q, Hash[params.map { |k,v| [k.to_s, v.to_s] }])
end

#algolia_reindex(batch_size = 1000, synchronous = false) ⇒ Object

reindex whole database using a extra temporary index + move operation



500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/algoliasearch-rails.rb', line 500

def algolia_reindex(batch_size = 1000, synchronous = false)
  return if algolia_without_auto_index_scope
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    next if options[:slave] || options[:replica]

    # fetch the master settings
    master_index = algolia_ensure_init(options, settings)
    master_settings = master_index.get_settings rescue {} # if master doesn't exist yet
    master_settings.merge!(JSON.parse(settings.to_settings.to_json)) # convert symbols to strings

    # remove the replicas of the temporary index
    master_settings.delete :slaves
    master_settings.delete 'slaves'
    master_settings.delete :replicas
    master_settings.delete 'replicas'

    # init temporary index
    index_name = algolia_index_name(options)
    tmp_options = options.merge({ :index_name => "#{index_name}.tmp" })
    tmp_options.delete(:per_environment) # already included in the temporary index_name
    tmp_settings = settings.dup
    tmp_index = algolia_ensure_init(tmp_options, tmp_settings, master_settings)

    algolia_find_in_batches(batch_size) do |group|
      if algolia_conditional_index?(tmp_options)
        # select only indexable objects
        group = group.select { |o| algolia_indexable?(o, tmp_options) }
      end
      objects = group.map { |o| tmp_settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, tmp_options) }
      tmp_index.save_objects(objects)
    end

    move_task = SafeIndex.move_index(tmp_index.name, index_name)
    master_index.wait_task(move_task["taskID"]) if synchronous || options[:synchronous]
  end
  nil
end

#algolia_reindex!(batch_size = 1000, synchronous = false) ⇒ Object



469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/algoliasearch-rails.rb', line 469

def algolia_reindex!(batch_size = 1000, synchronous = false)
  return if algolia_without_auto_index_scope
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    index = algolia_ensure_init(options, settings)
    next if options[:slave] || options[:replica]
    last_task = nil

    algolia_find_in_batches(batch_size) do |group|
      if algolia_conditional_index?(options)
        # delete non-indexable objects
        ids = group.select { |o| !algolia_indexable?(o, options) }.map { |o| algolia_object_id_of(o, options) }
        index.delete_objects(ids.select { |id| !id.blank? })
        # select only indexable objects
        group = group.select { |o| algolia_indexable?(o, options) }
      end
      objects = group.map do |o|
        attributes = settings.get_attributes(o)
        unless attributes.class == Hash
          attributes = attributes.to_hash
        end
        attributes.merge 'objectID' => algolia_object_id_of(o, options)
      end
      last_task = index.save_objects(objects)
    end
    index.wait_task(last_task["taskID"]) if last_task and (synchronous || options[:synchronous])
  end
  nil
end

#algolia_remove_from_index!(object, synchronous = false) ⇒ Object

Raises:

  • (ArgumentError)


575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# File 'lib/algoliasearch-rails.rb', line 575

def algolia_remove_from_index!(object, synchronous = false)
  return if algolia_without_auto_index_scope
  object_id = algolia_object_id_of(object)
  raise ArgumentError.new("Cannot index a record with a blank objectID") if object_id.blank?
  algolia_configurations.each do |options, settings|
    next if algolia_indexing_disabled?(options)
    index = algolia_ensure_init(options, settings)
    next if options[:slave] || options[:replica]
    if synchronous || options[:synchronous]
      index.delete_object!(object_id)
    else
      index.delete_object(object_id)
    end
  end
  nil
end

#algolia_search(q, params = {}) ⇒ Object



636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/algoliasearch-rails.rb', line 636

def algolia_search(q, params = {})
  if AlgoliaSearch.configuration[:pagination_backend]
    # kaminari and will_paginate start pagination at 1, Algolia starts at 0
    params[:page] = (params.delete('page') || params.delete(:page)).to_i
    params[:page] -= 1 if params[:page].to_i > 0
  end
  json = algolia_raw_search(q, params)
  hit_ids = json['hits'].map { |hit| hit['objectID'] }
  if defined?(::Mongoid::Document) && self.include?(::Mongoid::Document)
    condition_key = algolia_object_id_method.in
  else
    condition_key = algolia_object_id_method
  end
  results_by_id = algoliasearch_options[:type].where(condition_key => hit_ids).index_by do |hit|
    algolia_object_id_of(hit)
  end
  results = json['hits'].map do |hit|
    o = results_by_id[hit['objectID'].to_s]
    if o
      o.highlight_result = hit['_highlightResult']
      o.snippet_result = hit['_snippetResult']
      o
    end
  end.compact
  # Algolia has a default limit of 1000 retrievable hits
  total_hits = json['nbHits'].to_i < json['nbPages'].to_i * json['hitsPerPage'].to_i ?
    json['nbHits'].to_i: json['nbPages'].to_i * json['hitsPerPage'].to_i
  res = AlgoliaSearch::Pagination.create(results, total_hits, algoliasearch_options.merge({ :page => json['page'].to_i + 1, :per_page => json['hitsPerPage'] }))
  res.extend(AdditionalMethods)
  res.send(:algolia_init_raw_answer, json)
  res
end

#algolia_search_for_facet_values(facet, text, params = {}) ⇒ Object Also known as: algolia_search_facet



669
670
671
672
673
674
675
676
677
678
679
# File 'lib/algoliasearch-rails.rb', line 669

def algolia_search_for_facet_values(facet, text, params = {})
  index_name = params.delete(:index) ||
               params.delete('index') ||
               params.delete(:slave) ||
               params.delete('slave') ||
               params.delete(:replica) ||
               params.delete('replicas')
  index = algolia_index(index_name)
  query = Hash[params.map { |k, v| [k.to_s, v.to_s] }]
  index.search_facet(facet, text, query)['facetHits']
end

#algolia_without_auto_index(&block) ⇒ Object



452
453
454
455
456
457
458
459
# File 'lib/algoliasearch-rails.rb', line 452

def algolia_without_auto_index(&block)
  self.algolia_without_auto_index_scope = true
  begin
    yield
  ensure
    self.algolia_without_auto_index_scope = false
  end
end

#algolia_without_auto_index_scopeObject



465
466
467
# File 'lib/algoliasearch-rails.rb', line 465

def algolia_without_auto_index_scope
  Thread.current["algolia_without_auto_index_scope_for_#{self.model_name}"]
end

#algolia_without_auto_index_scope=(value) ⇒ Object



461
462
463
# File 'lib/algoliasearch-rails.rb', line 461

def algolia_without_auto_index_scope=(value)
  Thread.current["algolia_without_auto_index_scope_for_#{self.model_name}"] = value
end

#algoliasearch(options = {}, &block) ⇒ Object



363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
# File 'lib/algoliasearch-rails.rb', line 363

def algoliasearch(options = {}, &block)
  self.algoliasearch_settings = IndexSettings.new(options, block_given? ? Proc.new : nil)
  self.algoliasearch_options = { :type => algolia_full_const_get(model_name.to_s), :per_page => algoliasearch_settings.get_setting(:hitsPerPage) || 10, :page => 1 }.merge(options)

  attr_accessor :highlight_result, :snippet_result

  if options[:synchronous] == true
    if defined?(::Sequel) && self < Sequel::Model
      class_eval do
        copy_after_validation = instance_method(:after_validation)
        define_method(:after_validation) do |*args|
          super(*args)
          copy_after_validation.bind(self).call
          algolia_mark_synchronous
        end
      end
    else
      after_validation :algolia_mark_synchronous if respond_to?(:after_validation)
    end
  end
  if options[:enqueue]
    raise ArgumentError.new("Cannot use a enqueue if the `synchronous` option if set") if options[:synchronous]
    proc = if options[:enqueue] == true
      Proc.new do |record, remove|
        AlgoliaJob.perform_later(record, remove ? 'algolia_remove_from_index!' : 'algolia_index!')
      end
    elsif options[:enqueue].respond_to?(:call)
      options[:enqueue]
    elsif options[:enqueue].is_a?(Symbol)
      Proc.new { |record, remove| self.send(options[:enqueue], record, remove) }
    else
      raise ArgumentError.new("Invalid `enqueue` option: #{options[:enqueue]}")
    end
    algoliasearch_options[:enqueue] = Proc.new do |record, remove|
      proc.call(record, remove) unless algolia_without_auto_index_scope
    end
  end
  unless options[:auto_index] == false
    if defined?(::Sequel) && self < Sequel::Model
      class_eval do
        copy_after_validation = instance_method(:after_validation)
        copy_before_save = instance_method(:before_save)
        copy_after_commit = instance_method(:after_commit)

        define_method(:after_validation) do |*args|
          super(*args)
          copy_after_validation.bind(self).call
          algolia_mark_must_reindex
        end

        define_method(:before_save) do |*args|
          copy_before_save.bind(self).call
          algolia_mark_for_auto_indexing
          super(*args)
        end

        define_method(:after_commit) do |*args|
          super(*args)
          copy_after_commit.bind(self).call
          algolia_perform_index_tasks
        end
      end
    else
      after_validation :algolia_mark_must_reindex if respond_to?(:after_validation)
      before_save :algolia_mark_for_auto_indexing if respond_to?(:before_save)
      if respond_to?(:after_commit)
        after_commit :algolia_perform_index_tasks
      elsif respond_to?(:after_save)
        after_save :algolia_perform_index_tasks
      end
    end
  end
  unless options[:auto_remove] == false
    if defined?(::Sequel) && self < Sequel::Model
      class_eval do
        copy_after_destroy = instance_method(:after_destroy)

        define_method(:after_destroy) do |*args|
          copy_after_destroy.bind(self).call
          algolia_enqueue_remove_from_index!(algolia_synchronous?)
          super(*args)
        end
      end
    else
      after_destroy { |searchable| searchable.algolia_enqueue_remove_from_index!(algolia_synchronous?) } if respond_to?(:after_destroy)
    end
  end
end