Class: AlgoliaSearch::IndexSettings

Inherits:
Object
  • Object
show all
Defined in:
lib/algoliasearch-rails.rb

Constant Summary collapse

DEFAULT_BATCH_SIZE =
1000
OPTIONS =

AlgoliaSearch settings

[
  # Attributes
  :searchableAttributes, :attributesForFaceting, :unretrievableAttributes, :attributesToRetrieve,
  :attributesToIndex, #Legacy name of searchableAttributes
  # Ranking
  :ranking, :customRanking, # Replicas are handled via `add_replica`
  # Faceting
  :maxValuesPerFacet, :sortFacetValuesBy,
  # Highlighting / Snippeting
  :attributesToHighlight, :attributesToSnippet, :highlightPreTag, :highlightPostTag,
  :snippetEllipsisText, :restrictHighlightAndSnippetArrays,
  # Pagination
  :hitsPerPage, :paginationLimitedTo,
  # Typo
  :minWordSizefor1Typo, :minWordSizefor2Typos, :typoTolerance, :allowTyposOnNumericTokens,
  :disableTypoToleranceOnAttributes, :disableTypoToleranceOnWords, :separatorsToIndex,
  # Language
  :ignorePlurals, :removeStopWords, :camelCaseAttributes, :decompoundedAttributes,
  :keepDiacriticsOnCharacters, :queryLanguages,
  # Query Rules
  :enableRules,
  # Query Strategy
  :queryType, :removeWordsIfNoResults, :advancedSyntax, :optionalWords,
  :disablePrefixOnAttributes, :disableExactOnAttributes, :exactOnSingleWordQuery, :alternativesAsExact,
  # Performance
  :numericAttributesForFiltering, :allowCompressionOfIntegerArray,
  :numericAttributesToIndex, # Legacy name of numericAttributesForFiltering
  # Advanced
  :attributeForDistinct, :distinct, :replaceSynonymsInHighlight, :minProximity, :responseFields,
  :maxFacetHits,

  # Rails-specific
  :synonyms, :placeholders, :altCorrections,
]

Instance Method Summary collapse

Constructor Details

#initialize(options, block) ⇒ IndexSettings

Returns a new instance of IndexSettings.



93
94
95
96
# File 'lib/algoliasearch-rails.rb', line 93

def initialize(options, block)
  @options = options
  instance_exec(&block) if block
end

Instance Method Details

#add_attribute(*names, &block) ⇒ Object Also known as: add_attributes

Raises:

  • (ArgumentError)


113
114
115
116
117
118
119
120
# File 'lib/algoliasearch-rails.rb', line 113

def add_attribute(*names, &block)
  raise ArgumentError.new('Cannot pass multiple attribute names if block given') if block_given? and names.length > 1
  raise ArgumentError.new('Cannot specify additional attributes on a replica index') if @options[:slave] || @options[:replica]
  @additional_attributes ||= {}
  names.each do |name|
    @additional_attributes[name.to_s] = block_given? ? Proc.new { |o| o.instance_eval(&block) } : Proc.new { |o| o.send(name) }
  end
end

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

Raises:

  • (ArgumentError)


268
269
270
271
272
273
274
275
276
# File 'lib/algoliasearch-rails.rb', line 268

def add_index(index_name, options = {}, &block)
  raise ArgumentError.new('Cannot specify additional index on a replica index') if @options[:slave] || @options[:replica]
  raise ArgumentError.new('No block given') if !block_given?
  raise ArgumentError.new('Options auto_index and auto_remove cannot be set on nested indexes') if options[:auto_index] || options[:auto_remove]
  @additional_indexes ||= {}
  raise MixedSlavesAndReplicas.new('Cannot mix slaves and replicas in the same configuration (add_slave is deprecated)') if (options[:slave] && @additional_indexes.any? { |opts, _| opts[:replica] }) || (options[:replica] && @additional_indexes.any? { |opts, _| opts[:slave] })
  options[:index_name] = index_name
  @additional_indexes[options] = IndexSettings.new(options, Proc.new)
end

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

Raises:

  • (ArgumentError)


278
279
280
281
282
# File 'lib/algoliasearch-rails.rb', line 278

def add_replica(index_name, options = {}, &block)
  raise ArgumentError.new('Cannot specify additional replicas on a replica index') if @options[:slave] || @options[:replica]
  raise ArgumentError.new('No block given') if !block_given?
  add_index(index_name, options.merge({ :replica => true, :primary_settings => self }), &block)
end

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

Raises:

  • (ArgumentError)


284
285
286
287
288
# File 'lib/algoliasearch-rails.rb', line 284

def add_slave(index_name, options = {}, &block)
  raise ArgumentError.new('Cannot specify additional slaves on a slave index') if @options[:slave] || @options[:replica]
  raise ArgumentError.new('No block given') if !block_given?
  add_index(index_name, options.merge({ :slave => true, :primary_settings => self }), &block)
end

#additional_indexesObject



290
291
292
# File 'lib/algoliasearch-rails.rb', line 290

def additional_indexes
  @additional_indexes || {}
end

#attribute(*names, &block) ⇒ Object Also known as: attributes

Raises:

  • (ArgumentError)


103
104
105
106
107
108
109
110
# File 'lib/algoliasearch-rails.rb', line 103

def attribute(*names, &block)
  raise ArgumentError.new('Cannot pass multiple attribute names if block given') if block_given? and names.length > 1
  raise ArgumentError.new('Cannot specify additional attributes on a replica index') if @options[:slave] || @options[:replica]
  @attributes ||= {}
  names.flatten.each do |name|
    @attributes[name.to_s] = block_given? ? Proc.new { |o| o.instance_eval(&block) } : Proc.new { |o| o.send(name) }
  end
end

#attributes_to_hash(attributes, object) ⇒ Object



152
153
154
155
156
157
158
# File 'lib/algoliasearch-rails.rb', line 152

def attributes_to_hash(attributes, object)
  if attributes
    Hash[attributes.map { |name, value| [name.to_s, value.call(object) ] }]
  else
    {}
  end
end

#encode_attributes(v) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/algoliasearch-rails.rb', line 213

def encode_attributes(v)
  case v
  when String
    v.force_encoding('utf-8')
  when Hash
    v.each { |key, value| v[key] = encode_attributes(value) }
  when Array
    v.map { |x| encode_attributes(x) }
  else
    v
  end
end

#geoloc(lat_attr, lng_attr) ⇒ Object

Raises:

  • (ArgumentError)


226
227
228
229
230
231
# File 'lib/algoliasearch-rails.rb', line 226

def geoloc(lat_attr, lng_attr)
  raise ArgumentError.new('Cannot specify additional attributes on a replica index') if @options[:slave] || @options[:replica]
  add_attribute :_geoloc do |o|
    { :lat => o.send(lat_attr).to_f, :lng => o.send(lng_attr).to_f }
  end
end

#get_attribute_names(object) ⇒ Object



148
149
150
# File 'lib/algoliasearch-rails.rb', line 148

def get_attribute_names(object)
  get_attributes(object).keys
end

#get_attributes(object) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/algoliasearch-rails.rb', line 160

def get_attributes(object)
  # If a serializer is set, we ignore attributes
  # everything should be done via the serializer
  if not @serializer.nil?
    attributes = @serializer.new(object).attributes
  else
    if @attributes.nil? || @attributes.length == 0
      # no `attribute ...` have been configured, use the default attributes of the model
      attributes = get_default_attributes(object)
    else
      # at least 1 `attribute ...` has been configured, therefore use ONLY the one configured
      if is_active_record?(object)
        object.class.unscoped do
          attributes = attributes_to_hash(@attributes, object)
        end
      else
        attributes = attributes_to_hash(@attributes, object)
      end
    end
  end

  attributes.merge!(attributes_to_hash(@additional_attributes, object)) if @additional_attributes

  if @options[:sanitize]
    sanitizer = begin
      ::HTML::FullSanitizer.new
    rescue NameError
      # from rails 4.2
      ::Rails::Html::FullSanitizer.new
    end
    attributes = sanitize_attributes(attributes, sanitizer)
  end

  if @options[:force_utf8_encoding] && Object.const_defined?(:RUBY_VERSION) && RUBY_VERSION.to_f > 1.8
    attributes = encode_attributes(attributes)
  end

  attributes
end

#get_default_attributes(object) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/algoliasearch-rails.rb', line 135

def get_default_attributes(object)
  if is_mongoid?(object)
    # work-around mongoid 2.4's unscoped method, not accepting a block
    object.attributes
  elsif is_sequel?(object)
    object.to_hash
  else
    object.class.unscoped do
      object.attributes
    end
  end
end

#get_setting(name) ⇒ Object



241
242
243
# File 'lib/algoliasearch-rails.rb', line 241

def get_setting(name)
  instance_variable_get("@#{name}")
end

#is_active_record?(object) ⇒ Boolean

Returns:

  • (Boolean)


131
132
133
# File 'lib/algoliasearch-rails.rb', line 131

def is_active_record?(object)
  !is_mongoid?(object) && !is_sequel?(object)
end

#is_mongoid?(object) ⇒ Boolean

Returns:

  • (Boolean)


123
124
125
# File 'lib/algoliasearch-rails.rb', line 123

def is_mongoid?(object)
  defined?(::Mongoid::Document) && object.class.include?(::Mongoid::Document)
end

#is_sequel?(object) ⇒ Boolean

Returns:

  • (Boolean)


127
128
129
# File 'lib/algoliasearch-rails.rb', line 127

def is_sequel?(object)
  defined?(::Sequel) && object.class < ::Sequel::Model
end

#sanitize_attributes(v, sanitizer) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/algoliasearch-rails.rb', line 200

def sanitize_attributes(v, sanitizer)
  case v
  when String
    sanitizer.sanitize(v)
  when Hash
    v.each { |key, value| v[key] = sanitize_attributes(value, sanitizer) }
  when Array
    v.map { |x| sanitize_attributes(x, sanitizer) }
  else
    v
  end
end

#tags(*args, &block) ⇒ Object

Raises:

  • (ArgumentError)


233
234
235
236
237
238
239
# File 'lib/algoliasearch-rails.rb', line 233

def tags(*args, &block)
  raise ArgumentError.new('Cannot specify additional attributes on a replica index') if @options[:slave] || @options[:replica]
  add_attribute :_tags do |o|
    v = block_given? ? o.instance_eval(&block) : args
    v.is_a?(Array) ? v : [v]
  end
end

#to_settingsObject



245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/algoliasearch-rails.rb', line 245

def to_settings
  settings = {}
  OPTIONS.each do |k|
    v = get_setting(k)
    settings[k] = v if !v.nil?
  end
  if !@options[:slave] && !@options[:replica]
    settings[:slaves] = additional_indexes.select { |opts, s| opts[:slave] }.map do |opts, s|
      name = opts[:index_name]
      name = "#{name}_#{Rails.env.to_s}" if opts[:per_environment]
      name
    end
    settings.delete(:slaves) if settings[:slaves].empty?
    settings[:replicas] = additional_indexes.select { |opts, s| opts[:replica] }.map do |opts, s|
      name = opts[:index_name]
      name = "#{name}_#{Rails.env.to_s}" if opts[:per_environment]
      name
    end
    settings.delete(:replicas) if settings[:replicas].empty?
  end
  settings
end

#use_serializer(serializer) ⇒ Object



98
99
100
101
# File 'lib/algoliasearch-rails.rb', line 98

def use_serializer(serializer)
  @serializer = serializer
  # instance_variable_set("@serializer", serializer)
end