repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/notifications_test.rb
test/notifications_test.rb
require_relative "test_helper" class NotificationsTest < Minitest::Test def test_search Product.searchkick_index.refresh notifications = capture_notifications do Product.search("product").to_a end assert_equal 1, notifications.size assert_equal "search.searchkick", notifications.last[:name] end private def capture_notifications notifications = [] callback = lambda do |name, started, finished, unique_id, payload| notifications << {name: name, payload: payload} end ActiveSupport::Notifications.subscribed(callback, /searchkick/) do yield end notifications end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/parameters_test.rb
test/parameters_test.rb
require_relative "test_helper" class ParametersTest < Minitest::Test def setup require "action_controller" super end def test_options params = ActionController::Parameters.new({store_id: 1}) assert_raises(ActionController::UnfilteredParameters) do Product.search("*", **params) end end def test_where params = ActionController::Parameters.new({store_id: 1}) assert_raises(ActionController::UnfilteredParameters) do Product.search("*", where: params) end end def test_where_relation params = ActionController::Parameters.new({store_id: 1}) assert_raises(ActionController::UnfilteredParameters) do Product.search("*").where(params) end end def test_rewhere_relation params = ActionController::Parameters.new({store_id: 1}) assert_raises(ActionController::UnfilteredParameters) do Product.search("*").where(params) end end def test_where_permitted store [{name: "Product A", store_id: 1}, {name: "Product B", store_id: 2}] params = ActionController::Parameters.new({store_id: 1}) assert_search "product", ["Product A"], where: params.permit(:store_id) end def test_where_permitted_relation store [{name: "Product A", store_id: 1}, {name: "Product B", store_id: 2}] params = ActionController::Parameters.new({store_id: 1}) assert_search_relation ["Product A"], Product.search("product").where(params.permit(:store_id)) end def test_rewhere_permitted_relation store [{name: "Product A", store_id: 1}, {name: "Product B", store_id: 2}] params = ActionController::Parameters.new({store_id: 1}) assert_search_relation ["Product A"], Product.search("product").rewhere(params.permit(:store_id)) end def test_where_value store [{name: "Product A", store_id: 1}, {name: "Product B", store_id: 2}] params = ActionController::Parameters.new({store_id: 1}) assert_search "product", ["Product A"], where: {store_id: params[:store_id]} end def test_where_value_relation store [{name: "Product A", store_id: 1}, {name: "Product B", store_id: 2}] params = ActionController::Parameters.new({store_id: 1}) assert_search_relation ["Product A"], Product.search("product").where(store_id: params[:store_id]) end def test_rewhere_value_relation store [{name: "Product A", store_id: 1}, {name: "Product B", store_id: 2}] params = ActionController::Parameters.new({store_id: 1}) assert_search_relation ["Product A"], Product.search("product").where(store_id: params[:store_id]) end def test_where_hash params = ActionController::Parameters.new({store_id: {value: 10, boost: 2}}) error = assert_raises(TypeError) do assert_search "product", [], where: {store_id: params[:store_id]} end assert_equal error.message, "can't cast ActionController::Parameters" end # TODO raise error without to_a def test_where_hash_relation params = ActionController::Parameters.new({store_id: {value: 10, boost: 2}}) error = assert_raises(TypeError) do Product.search("product").where(store_id: params[:store_id]).to_a end assert_equal error.message, "can't cast ActionController::Parameters" end # TODO raise error without to_a def test_rewhere_hash_relation params = ActionController::Parameters.new({store_id: {value: 10, boost: 2}}) error = assert_raises(TypeError) do Product.search("product").rewhere(store_id: params[:store_id]).to_a end assert_equal error.message, "can't cast ActionController::Parameters" end def test_aggs_where params = ActionController::Parameters.new({store_id: 1}) assert_raises(ActionController::UnfilteredParameters) do Product.search("*", aggs: {size: {where: params}}) end end def test_aggs_where_smart_aggs_false params = ActionController::Parameters.new({store_id: 1}) assert_raises(ActionController::UnfilteredParameters) do Product.search("*", aggs: {size: {where: params}}, smart_aggs: false) end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/multi_indices_test.rb
test/multi_indices_test.rb
require_relative "test_helper" class MultiIndicesTest < Minitest::Test def setup super setup_speaker end def test_basic store_names ["Product A"] store_names ["Product B"], Speaker assert_search_multi "product", ["Product A", "Product B"] end def test_index_name store_names ["Product A"] assert_equal ["Product A"], Product.search("product", index_name: Product.searchkick_index.name).map(&:name) assert_equal ["Product A"], Product.search("product", index_name: Product).map(&:name) Speaker.searchkick_index.refresh assert_equal [], Product.search("product", index_name: Speaker.searchkick_index.name, conversions: false).map(&:name) end def test_models_and_index_name store_names ["Product A"] store_names ["Product B"], Speaker assert_equal ["Product A"], Searchkick.search("product", models: [Product, Store], index_name: Product.searchkick_index.name).map(&:name) error = assert_raises(Searchkick::Error) do Searchkick.search("product", models: [Product, Store], index_name: Speaker.searchkick_index.name).map(&:name) end assert_includes error.message, "Unknown model" # legacy assert_equal ["Product A"], Searchkick.search("product", index_name: [Product, Store]).map(&:name) end def test_model_with_another_model error = assert_raises(ArgumentError) do Product.search(models: [Store]) end assert_includes error.message, "Use Searchkick.search" end def test_model_with_another_model_in_index_name error = assert_raises(ArgumentError) do # legacy protection Product.search(index_name: [Store, "another"]) end assert_includes error.message, "Use Searchkick.search" end def test_no_models_or_index_name store_names ["Product A"] error = assert_raises(Searchkick::Error) do Searchkick.search("product").to_a end assert_includes error.message, "Unknown model" end def test_no_models_or_index_name_load_false store_names ["Product A"] Searchkick.search("product", load: false).to_a end private def assert_search_multi(term, expected, options = {}) options[:models] = [Product, Speaker] options[:fields] = [:name] assert_search(term, expected, options, Searchkick) end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/index_cache_test.rb
test/index_cache_test.rb
require_relative "test_helper" class IndexCacheTest < Minitest::Test def setup Product.class_variable_get(:@@searchkick_index_cache).clear end def test_default object_id = Product.searchkick_index.object_id 3.times do assert_equal object_id, Product.searchkick_index.object_id end end def test_max_size starting_ids = object_ids(20) assert_equal starting_ids, object_ids(20) Product.searchkick_index(name: "other") refute_equal starting_ids, object_ids(20) end def test_thread_safe object_ids = with_threads { object_ids(20) } assert_equal object_ids[0], object_ids[1] assert_equal object_ids[0], object_ids[2] end # object ids can differ since threads progress at different speeds # test to make sure doesn't crash def test_thread_safe_max_size with_threads { object_ids(1000) } end private def object_ids(count) count.times.map { |i| Product.searchkick_index(name: "index#{i}").object_id } end def with_threads previous = Thread.report_on_exception begin Thread.report_on_exception = true 3.times.map { Thread.new { yield } }.map(&:join).map(&:value) ensure Thread.report_on_exception = previous end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/multi_search_test.rb
test/multi_search_test.rb
require_relative "test_helper" class MultiSearchTest < Minitest::Test def test_basic store_names ["Product A"] store_names ["Store A"], Store products = Product.search("*") stores = Store.search("*") Searchkick.multi_search([products, stores]) assert_equal ["Product A"], products.map(&:name) assert_equal ["Store A"], stores.map(&:name) end def test_methods result = Product.search("*") query = Product.search("*") assert_empty(result.methods - query.methods) end def test_error store_names ["Product A"] products = Product.search("*") stores = Store.search("*", order: [:bad_field]) Searchkick.multi_search([products, stores]) assert !products.error assert stores.error end def test_misspellings_below_unmet store_names ["abc", "abd", "aee"] products = Product.search("abc", misspellings: {below: 5}) Searchkick.multi_search([products]) assert_equal ["abc", "abd"], products.map(&:name) end def test_misspellings_below_error products = Product.search("abc", order: [:bad_field], misspellings: {below: 1}) Searchkick.multi_search([products]) assert products.error end def test_query_error products = Product.search("*", order: {bad_field: :asc}) Searchkick.multi_search([products]) assert products.error error = assert_raises(Searchkick::Error) { products.to_a } assert_equal error.message, "Query error - use the error method to view it" end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/scroll_test.rb
test/scroll_test.rb
require_relative "test_helper" class ScrollTest < Minitest::Test def test_works store_names ["Product A", "Product B", "Product C", "Product D", "Product E", "Product F"] products = Product.search("product", order: {name: :asc}, scroll: '1m', per_page: 2) assert_equal ["Product A", "Product B"], products.map(&:name) assert_equal "product", products.entry_name assert_equal 2, products.size assert_equal 2, products.length assert_equal 6, products.total_count assert_equal 6, products.total_entries assert products.any? # scroll for next 2 products = products.scroll assert_equal ["Product C", "Product D"], products.map(&:name) # scroll for next 2 products = products.scroll assert_equal ["Product E", "Product F"], products.map(&:name) # scroll exhausted products = products.scroll assert_equal [], products.map(&:name) end def test_body store_names ["Product A", "Product B", "Product C", "Product D", "Product E", "Product F"] products = Product.search("product", body: {query: {match_all: {}}, sort: [{name: "asc"}]}, scroll: '1m', per_page: 2) assert_equal ["Product A", "Product B"], products.map(&:name) assert_equal "product", products.entry_name assert_equal 2, products.size assert_equal 2, products.length assert_equal 6, products.total_count assert_equal 6, products.total_entries assert products.any? # scroll for next 2 products = products.scroll assert_equal ["Product C", "Product D"], products.map(&:name) # scroll for next 2 products = products.scroll assert_equal ["Product E", "Product F"], products.map(&:name) # scroll exhausted products = products.scroll assert_equal [], products.map(&:name) end def test_all store_names ["Product A"] assert_equal ["Product A"], Product.search("*", scroll: "1m").map(&:name) end def test_all_relation store_names ["Product A"] assert_equal ["Product A"], Product.search("*").scroll("1m").map(&:name) end def test_no_option products = Product.search("*") error = assert_raises Searchkick::Error do products.scroll end assert_match(/Pass .+ option/, error.message) end def test_block store_names ["Product A", "Product B", "Product C", "Product D", "Product E", "Product F"] batches_count = 0 Product.search("*", scroll: "1m", per_page: 2).scroll do |batch| assert_equal 2, batch.size batches_count += 1 end assert_equal 3, batches_count end def test_block_relation store_names ["Product A", "Product B", "Product C", "Product D", "Product E", "Product F"] batches_count = 0 Product.search("*").per_page(2).scroll("1m") do |batch| assert_equal 2, batch.size batches_count += 1 end assert_equal 3, batches_count end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/order_test.rb
test/order_test.rb
require_relative "test_helper" class OrderTest < Minitest::Test def test_hash store_names ["Product A", "Product B", "Product C", "Product D"] assert_order "product", ["Product D", "Product C", "Product B", "Product A"], order: {name: :desc} assert_order_relation ["Product D", "Product C", "Product B", "Product A"], Product.search("product").order(name: :desc) end def test_string store_names ["Product A", "Product B", "Product C", "Product D"] assert_order "product", ["Product A", "Product B", "Product C", "Product D"], order: "name" assert_order_relation ["Product A", "Product B", "Product C", "Product D"], Product.search("product").order("name") end def test_multiple store [ {name: "Product A", color: "blue", store_id: 1}, {name: "Product B", color: "red", store_id: 3}, {name: "Product C", color: "red", store_id: 2} ] assert_order "product", ["Product A", "Product B", "Product C"], order: {color: :asc, store_id: :desc} assert_order_relation ["Product A", "Product B", "Product C"], Product.search("product").order(color: :asc, store_id: :desc) assert_order_relation ["Product A", "Product B", "Product C"], Product.search("product").order(:color, store_id: :desc) assert_order_relation ["Product A", "Product B", "Product C"], Product.search("product").order(color: :asc).order(store_id: :desc) assert_order_relation ["Product B", "Product C", "Product A"], Product.search("product").order(color: :asc).reorder(store_id: :desc) end def test_unmapped_type Product.searchkick_index.refresh assert_order "product", [], order: {not_mapped: {unmapped_type: "long"}} assert_order_relation [], Product.search("product").order(not_mapped: {unmapped_type: "long"}) end def test_array store [{name: "San Francisco", latitude: 37.7833, longitude: -122.4167}] assert_order "francisco", ["San Francisco"], order: [{_geo_distance: {location: "0,0"}}] assert_order_relation ["San Francisco"], Product.search("francisco").order([{_geo_distance: {location: "0,0"}}]) end def test_script store_names ["Red", "Green", "Blue"] order = {_script: {type: "number", script: {source: "doc['name'].value.length() * -1"}}} assert_order "*", ["Green", "Blue", "Red"], order: order assert_order_relation ["Green", "Blue", "Red"], Product.search("*").order(order) end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/marshal_test.rb
test/marshal_test.rb
require_relative "test_helper" class MarshalTest < Minitest::Test def test_marshal store_names ["Product A"] assert Marshal.dump(Product.search("*").to_a) end def test_marshal_highlights store_names ["Product A"] assert Marshal.dump(Product.search("product", highlight: true, load: {dumpable: true}).to_a) end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/partial_reindex_test.rb
test/partial_reindex_test.rb
require_relative "test_helper" class PartialReindexTest < Minitest::Test def test_record_inline store [{name: "Hi", color: "Blue"}] product = Product.first Searchkick.callbacks(false) do product.update!(name: "Bye", color: "Red") end product.reindex(:search_name, refresh: true) # name updated, but not color assert_search "bye", ["Bye"], fields: [:name], load: false assert_search "blue", ["Bye"], fields: [:color], load: false end def test_record_async store [{name: "Hi", color: "Blue"}] product = Product.first Searchkick.callbacks(false) do product.update!(name: "Bye", color: "Red") end perform_enqueued_jobs do product.reindex(:search_name, mode: :async) end Product.searchkick_index.refresh # name updated, but not color assert_search "bye", ["Bye"], fields: [:name], load: false assert_search "blue", ["Bye"], fields: [:color], load: false end def test_record_queue product = Product.create!(name: "Hi") error = assert_raises(Searchkick::Error) do product.reindex(:search_name, mode: :queue) end assert_equal "Partial reindex not supported with queue option", error.message end def test_record_missing_inline store [{name: "Hi", color: "Blue"}] product = Product.first Product.searchkick_index.remove(product) error = assert_raises(Searchkick::ImportError) do product.reindex(:search_name) end assert_match "document missing", error.message end def test_record_ignore_missing_inline store [{name: "Hi", color: "Blue"}] product = Product.first Product.searchkick_index.remove(product) product.reindex(:search_name, ignore_missing: true) Searchkick.callbacks(:bulk) do product.reindex(:search_name, ignore_missing: true) end end def test_record_missing_async store [{name: "Hi", color: "Blue"}] product = Product.first Product.searchkick_index.remove(product) perform_enqueued_jobs do error = assert_raises(Searchkick::ImportError) do product.reindex(:search_name, mode: :async) end assert_match "document missing", error.message end end def test_record_ignore_missing_async store [{name: "Hi", color: "Blue"}] product = Product.first Product.searchkick_index.remove(product) perform_enqueued_jobs do product.reindex(:search_name, mode: :async, ignore_missing: true) end end def test_relation_inline store [{name: "Hi", color: "Blue"}] product = Product.first Searchkick.callbacks(false) do product.update!(name: "Bye", color: "Red") end Product.reindex(:search_name) # name updated, but not color assert_search "bye", ["Bye"], fields: [:name], load: false assert_search "blue", ["Bye"], fields: [:color], load: false # scope Product.reindex(:search_name, scope: :all) end def test_relation_async store [{name: "Hi", color: "Blue"}] product = Product.first Searchkick.callbacks(false) do product.update!(name: "Bye", color: "Red") end perform_enqueued_jobs do Product.reindex(:search_name, mode: :async) end # name updated, but not color assert_search "bye", ["Bye"], fields: [:name], load: false assert_search "blue", ["Bye"], fields: [:color], load: false end def test_relation_queue Product.create!(name: "Hi") error = assert_raises(Searchkick::Error) do Product.reindex(:search_name, mode: :queue) end assert_equal "Partial reindex not supported with queue option", error.message end def test_relation_missing_inline store [{name: "Hi", color: "Blue"}] product = Product.first Product.searchkick_index.remove(product) error = assert_raises(Searchkick::ImportError) do Product.reindex(:search_name) end assert_match "document missing", error.message end def test_relation_ignore_missing_inline store [{name: "Hi", color: "Blue"}] product = Product.first Product.searchkick_index.remove(product) Product.where(id: product.id).reindex(:search_name, ignore_missing: true) end def test_relation_missing_async store [{name: "Hi", color: "Blue"}] product = Product.first Product.searchkick_index.remove(product) perform_enqueued_jobs do error = assert_raises(Searchkick::ImportError) do Product.reindex(:search_name, mode: :async) end assert_match "document missing", error.message end end def test_relation_ignore_missing_async store [{name: "Hi", color: "Blue"}] product = Product.first Product.searchkick_index.remove(product) perform_enqueued_jobs do Product.where(id: product.id).reindex(:search_name, mode: :async, ignore_missing: true) end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/callbacks_test.rb
test/callbacks_test.rb
require_relative "test_helper" class CallbacksTest < Minitest::Test def test_false Searchkick.callbacks(false) do store_names ["Product A", "Product B"] end assert_search "product", [] end def test_bulk Searchkick.callbacks(:bulk) do store_names ["Product A", "Product B"] end Product.searchkick_index.refresh assert_search "product", ["Product A", "Product B"] end def test_async assert_enqueued_jobs 2 do Searchkick.callbacks(:async) do store_names ["Product A", "Product B"] end end end def test_queue # TODO figure out which earlier test leaves records in index Product.reindex reindex_queue = Product.searchkick_index.reindex_queue reindex_queue.clear Searchkick.callbacks(:queue) do store_names ["Product A", "Product B"] end Product.searchkick_index.refresh assert_search "product", [], load: false, conversions: false assert_equal 2, reindex_queue.length perform_enqueued_jobs do Searchkick::ProcessQueueJob.perform_now(class_name: "Product") end Product.searchkick_index.refresh assert_search "product", ["Product A", "Product B"], load: false assert_equal 0, reindex_queue.length Searchkick.callbacks(:queue) do Product.where(name: "Product B").destroy_all Product.create!(name: "Product C") end Product.searchkick_index.refresh assert_search "product", ["Product A", "Product B"], load: false assert_equal 2, reindex_queue.length perform_enqueued_jobs do Searchkick::ProcessQueueJob.perform_now(class_name: "Product") end Product.searchkick_index.refresh assert_search "product", ["Product A", "Product C"], load: false assert_equal 0, reindex_queue.length # ensure no error with empty queue Searchkick::ProcessQueueJob.perform_now(class_name: "Product") end def test_record_async with_options({callbacks: :async}, Song) do assert_enqueued_jobs 1 do Song.create!(name: "Product A") end assert_enqueued_jobs 1 do Song.first.reindex end end end def test_relation_async with_options({callbacks: :async}, Song) do assert_enqueued_jobs 0 do Song.all.reindex end end end def test_disable_callbacks # make sure callbacks default to on assert Searchkick.callbacks? store_names ["Product A"] Searchkick.disable_callbacks assert !Searchkick.callbacks? store_names ["Product B"] assert_search "product", ["Product A"] Searchkick.enable_callbacks Product.reindex assert_search "product", ["Product A", "Product B"] end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/language_test.rb
test/language_test.rb
require_relative "test_helper" class LanguageTest < Minitest::Test def setup skip "Requires plugin" unless ci? || ENV["TEST_LANGUAGE"] Song.destroy_all end def test_chinese skip if ci? # requires https://github.com/medcl/elasticsearch-analysis-ik with_options({language: "chinese"}) do store_names ["中华人民共和国国歌"] assert_language_search "中华人民共和国", ["中华人民共和国国歌"] assert_language_search "国歌", ["中华人民共和国国歌"] assert_language_search "人", [] end end def test_chinese2 # requires https://www.elastic.co/guide/en/elasticsearch/plugins/7.4/analysis-smartcn.html with_options({language: "chinese2"}) do store_names ["中华人民共和国国歌"] assert_language_search "中华人民共和国", ["中华人民共和国国歌"] # assert_language_search "国歌", ["中华人民共和国国歌"] assert_language_search "人", [] end end def test_japanese # requires https://www.elastic.co/guide/en/elasticsearch/plugins/7.4/analysis-kuromoji.html with_options({language: "japanese"}) do store_names ["JR新宿駅の近くにビールを飲みに行こうか"] assert_language_search "飲む", ["JR新宿駅の近くにビールを飲みに行こうか"] assert_language_search "jr", ["JR新宿駅の近くにビールを飲みに行こうか"] assert_language_search "新", [] end end def test_japanese_search_synonyms # requires https://www.elastic.co/guide/en/elasticsearch/plugins/7.4/analysis-kuromoji.html with_options({language: "japanese", search_synonyms: [["飲む", "喰らう"]]}) do store_names ["JR新宿駅の近くにビールを飲みに行こうか"] assert_language_search "喰らう", ["JR新宿駅の近くにビールを飲みに行こうか"] assert_language_search "新", [] end end def test_korean skip if ci? # requires https://github.com/open-korean-text/elasticsearch-analysis-openkoreantext with_options({language: "korean"}) do store_names ["한국어를 처리하는 예시입니닼ㅋㅋ"] assert_language_search "처리", ["한국어를 처리하는 예시입니닼ㅋㅋ"] assert_language_search "한국어", ["한국어를 처리하는 예시입니닼ㅋㅋ"] assert_language_search "를", [] end end def test_korean2 skip if ci? # requires https://www.elastic.co/guide/en/elasticsearch/plugins/7.4/analysis-nori.html with_options({language: "korean2"}) do store_names ["한국어를 처리하는 예시입니닼ㅋㅋ"] assert_language_search "처리", ["한국어를 처리하는 예시입니닼ㅋㅋ"] assert_language_search "한국어", ["한국어를 처리하는 예시입니닼ㅋㅋ"] assert_language_search "를", [] end end def test_polish # requires https://www.elastic.co/guide/en/elasticsearch/plugins/7.4/analysis-stempel.html with_options({language: "polish"}) do store_names ["polski"] assert_language_search "polskimi", ["polski"] end end def test_ukrainian # requires https://www.elastic.co/guide/en/elasticsearch/plugins/7.4/analysis-ukrainian.html with_options({language: "ukrainian"}) do store_names ["ресторани"] assert_language_search "ресторан", ["ресторани"] end end def test_vietnamese skip if ci? # requires https://github.com/duydo/elasticsearch-analysis-vietnamese with_options({language: "vietnamese"}) do store_names ["công nghệ thông tin Việt Nam"] assert_language_search "công nghệ thông tin", ["công nghệ thông tin Việt Nam"] assert_language_search "công", [] end end def test_stemmer_hunspell skip if ci? with_options({stemmer: {type: "hunspell", locale: "en_US"}}) do store_names ["the foxes jumping quickly"] assert_language_search "fox", ["the foxes jumping quickly"] end end def test_stemmer_unknown_type error = assert_raises(ArgumentError) do with_options({stemmer: {type: "bad"}}) do end end assert_equal "Unknown stemmer: bad", error.message end def test_stemmer_language skip if ci? error = assert_raises(ArgumentError) do with_options({stemmer: {type: "hunspell", locale: "en_US"}, language: "english"}) do end end assert_equal "Can't pass both language and stemmer", error.message end def assert_language_search(term, expected) assert_search term, expected, {misspellings: false} end def default_model Song end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/exclude_test.rb
test/exclude_test.rb
require_relative "test_helper" class ExcludeTest < Minitest::Test def test_butter store_names ["Butter Tub", "Peanut Butter Tub"] assert_search "butter", ["Butter Tub"], exclude: ["peanut butter"] end def test_butter_word_start store_names ["Butter Tub", "Peanut Butter Tub"] assert_search "butter", ["Butter Tub"], exclude: ["peanut butter"], match: :word_start end def test_butter_exact store_names ["Butter Tub", "Peanut Butter Tub"] assert_search "butter", [], exclude: ["peanut butter"], fields: [{name: :exact}] end def test_same_exact store_names ["Butter Tub", "Peanut Butter Tub"] assert_search "Butter Tub", ["Butter Tub"], exclude: ["Peanut Butter Tub"], fields: [{name: :exact}] end def test_egg_word_start store_names ["eggs", "eggplant"] assert_search "egg", ["eggs"], exclude: ["eggplant"], match: :word_start end def test_string store_names ["Butter Tub", "Peanut Butter Tub"] assert_search "butter", ["Butter Tub"], exclude: "peanut butter" end def test_match_all store_names ["Butter"] assert_search "*", [], exclude: "butter" end def test_match_all_fields store_names ["Butter"] assert_search "*", [], fields: [:name], exclude: "butter" assert_search "*", ["Butter"], fields: [:color], exclude: "butter" end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/support/apartment.rb
test/support/apartment.rb
module Rails def self.env ENV["RACK_ENV"] end end tenants = ["tenant1", "tenant2"] Apartment.configure do |config| config.tenant_names = tenants config.database_schema_file = false config.excluded_models = ["Product", "Store", "Region", "Speaker", "Animal", "Dog", "Cat", "Sku", "Song", "Band"] end class Tenant < ActiveRecord::Base searchkick index_prefix: -> { Apartment::Tenant.current } end tenants.each do |tenant| begin Apartment::Tenant.create(tenant) rescue Apartment::TenantExists # do nothing end Apartment::Tenant.switch!(tenant) ActiveRecord::Schema.define do create_table :tenants, force: true do |t| t.string :name t.timestamps null: true end end Tenant.reindex end Apartment::Tenant.reset
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/support/activerecord.rb
test/support/activerecord.rb
require "active_record" # for debugging ActiveRecord::Base.logger = $logger # rails does this in activerecord/lib/active_record/railtie.rb ActiveRecord.default_timezone = :utc ActiveRecord::Base.time_zone_aware_attributes = true # migrations ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:" require_relative "apartment" if defined?(Apartment) ActiveRecord::Migration.verbose = ENV["VERBOSE"] ActiveRecord::Schema.define do create_table :products do |t| t.string :name t.integer :store_id t.boolean :in_stock t.boolean :backordered t.integer :orders_count t.decimal :found_rate t.integer :price t.string :color t.decimal :latitude, precision: 10, scale: 7 t.decimal :longitude, precision: 10, scale: 7 t.text :description t.text :alt_description t.text :embedding t.text :embedding2 t.text :embedding3 t.text :embedding4 t.timestamps null: true end create_table :stores do |t| t.string :name end create_table :regions do |t| t.string :name t.text :text end create_table :speakers do |t| t.string :name end create_table :animals do |t| t.string :name t.string :type end create_table :skus, id: :uuid do |t| t.string :name end create_table :songs do |t| t.string :name end create_table :bands do |t| t.string :name t.boolean :active end create_table :artists do |t| t.string :name t.boolean :active t.boolean :should_index end end class Product < ActiveRecord::Base belongs_to :store serialize :embedding, coder: JSON serialize :embedding2, coder: JSON serialize :embedding3, coder: JSON serialize :embedding4, coder: JSON end class Store < ActiveRecord::Base has_many :products end class Region < ActiveRecord::Base end class Speaker < ActiveRecord::Base end class Animal < ActiveRecord::Base end class Dog < Animal end class Cat < Animal end class Sku < ActiveRecord::Base end class Song < ActiveRecord::Base end class Band < ActiveRecord::Base default_scope { where(active: true).order(:name) } end class Artist < ActiveRecord::Base default_scope { where(active: true).order(:name) } end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/support/redis.rb
test/support/redis.rb
options = {} options[:logger] = $logger if !defined?(RedisClient) Searchkick.redis = if !defined?(Redis) RedisClient.config.new_pool elsif defined?(ConnectionPool) ConnectionPool.new { Redis.new(**options) } else Redis.new(**options) end module RedisInstrumentation def call(command, redis_config) $logger.info "[redis] #{command.inspect}" super end def call_pipelined(commands, redis_config) $logger.info "[redis] #{commands.inspect}" super end end RedisClient.register(RedisInstrumentation) if defined?(RedisClient)
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/support/mongoid.rb
test/support/mongoid.rb
Mongoid.logger = $logger Mongo::Logger.logger = $logger if defined?(Mongo::Logger) Mongoid.configure do |config| config.connect_to "searchkick_test", server_selection_timeout: 1 end class Product include Mongoid::Document include Mongoid::Timestamps field :name field :store_id, type: Integer field :in_stock, type: Boolean field :backordered, type: Boolean field :orders_count, type: Integer field :found_rate, type: BigDecimal field :price, type: Integer field :color field :latitude, type: BigDecimal field :longitude, type: BigDecimal field :description field :alt_description field :embedding, type: Array field :embedding2, type: Array field :embedding3, type: Array field :embedding4, type: Array end class Store include Mongoid::Document has_many :products field :name end class Region include Mongoid::Document field :name field :text end class Speaker include Mongoid::Document field :name end class Animal include Mongoid::Document field :name end class Dog < Animal end class Cat < Animal end class Sku include Mongoid::Document field :name end class Song include Mongoid::Document field :name end class Band include Mongoid::Document field :name field :active, type: Mongoid::Boolean default_scope -> { where(active: true).order(name: 1) } end class Artist include Mongoid::Document field :name field :active, type: Mongoid::Boolean field :should_index, type: Mongoid::Boolean default_scope -> { where(active: true).order(name: 1) } end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/support/helpers.rb
test/support/helpers.rb
class Minitest::Test include ActiveJob::TestHelper def setup [Product, Store].each do |model| setup_model(model) end end protected def setup_animal setup_model(Animal) end def setup_region setup_model(Region) end def setup_speaker setup_model(Speaker) end def setup_model(model) # reindex once ($setup_model ||= {})[model] ||= (model.reindex || true) # clear every time Searchkick.callbacks(:bulk) do model.destroy_all end end def store(documents, model = default_model, reindex: true) if reindex with_callbacks(:bulk) do with_transaction(model) do model.create!(documents.shuffle) end end model.searchkick_index.refresh else Searchkick.callbacks(false) do with_transaction(model) do model.create!(documents.shuffle) end end end end def store_names(names, model = default_model, reindex: true) store names.map { |name| {name: name} }, model, reindex: reindex end # no order def assert_search(term, expected, options = {}, model = default_model) assert_equal expected.sort, model.search(term, **options).map(&:name).sort relation = model.search(term) options.each do |k, v| relation = relation.public_send(k, v) end assert_equal expected.sort, relation.map(&:name).sort end def assert_search_relation(expected, relation) assert_equal expected.sort, relation.map(&:name).sort end def assert_order(term, expected, options = {}, model = default_model) assert_equal expected, model.search(term, **options).map(&:name) relation = model.search(term) options.each do |k, v| relation = relation.public_send(k, v) end assert_equal expected, relation.map(&:name) end def assert_order_relation(expected, relation) assert_equal expected, relation.map(&:name) end def assert_equal_scores(term, options = {}, model = default_model) assert_equal 1, model.search(term, **options).hits.map { |a| a["_score"] }.uniq.size end def assert_first(term, expected, options = {}, model = default_model) assert_equal expected, model.search(term, **options).map(&:name).first end def assert_misspellings(term, expected, misspellings = {}, model = default_model) options = { fields: [:name, :color], misspellings: misspellings } assert_search(term, expected, options, model) end def assert_warns(message) _, stderr = capture_io do yield end assert_match "[searchkick] WARNING: #{message}", stderr end def with_options(options, model = default_model) previous_options = model.searchkick_options.dup begin model.instance_variable_set(:@searchkick_index_name, nil) model.searchkick_options.merge!(options) model.reindex yield ensure model.instance_variable_set(:@searchkick_index_name, nil) model.searchkick_options.clear model.searchkick_options.merge!(previous_options) end end def with_callbacks(value, &block) if Searchkick.callbacks?(default: nil).nil? Searchkick.callbacks(value, &block) else yield end end def with_transaction(model, &block) if model.respond_to?(:transaction) && !mongoid? model.transaction(&block) else yield end end def activerecord? defined?(ActiveRecord) end def mongoid? defined?(Mongoid) end def default_model Product end def ci? ENV["CI"] end # for Active Job helpers def tagged_logger end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/models/artist.rb
test/models/artist.rb
class Artist searchkick unscope: true def should_index? should_index end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/models/region.rb
test/models/region.rb
class Region searchkick \ geo_shape: [:territory] attr_accessor :territory def search_data { name: name, text: text, territory: territory } end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/models/speaker.rb
test/models/speaker.rb
class Speaker searchkick \ conversions_v1: ["conversions_a", "conversions_b"], search_synonyms: [ ["clorox", "bleach"], ["burger", "hamburger"], ["bandaids", "bandages"], ["UPPERCASE", "lowercase"], "led => led,lightbulb", "halogen lamp => lightbulb", ["United States of America", "USA"] ], word_start: [:name] attr_accessor :conversions_a, :conversions_b, :aisle def search_data serializable_hash.except("id", "_id").merge( conversions_a: conversions_a, conversions_b: conversions_b, aisle: aisle ) end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/models/animal.rb
test/models/animal.rb
class Animal searchkick \ inheritance: true, text_start: [:name], suggest: [:name] end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/models/store.rb
test/models/store.rb
class Store mappings = { properties: { name: {type: "text"} } } searchkick \ routing: true, merge_mappings: true, mappings: mappings def search_document_id id end def search_routing name end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/models/sku.rb
test/models/sku.rb
class Sku searchkick callbacks: :async end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/models/product.rb
test/models/product.rb
class Product searchkick \ synonyms: [ ["clorox", "bleach"], ["burger", "hamburger"], ["bandaid", "bandages"], ["UPPERCASE", "lowercase"], "lightbulb => led,lightbulb", "lightbulb => halogenlamp" ], suggest: [:name, :color], conversions_v1: [:conversions], conversions_v2: [:conversions_v2], locations: [:location, :multiple_locations], text_start: [:name], text_middle: [:name], text_end: [:name], word_start: [:name], word_middle: [:name], word_end: [:name], highlight: [:name], filterable: [:name, :color, :description], similarity: "BM25", match: ENV["MATCH"] ? ENV["MATCH"].to_sym : nil, knn: Searchkick.knn_support? ? { embedding: {dimensions: 3, distance: "cosine", m: 16, ef_construction: 100}, embedding2: {dimensions: 3, distance: "inner_product"}, embedding3: {dimensions: 3, distance: "euclidean"} }.merge(Searchkick.opensearch? ? {} : {embedding4: {dimensions: 3}}) : nil attr_accessor :conversions, :conversions_v2, :user_ids, :aisle, :details class << self attr_accessor :dynamic_data end def search_data return self.class.dynamic_data.call if self.class.dynamic_data serializable_hash.except("id", "_id").merge( conversions: conversions, conversions_v2: conversions_v2, user_ids: user_ids, location: {lat: latitude, lon: longitude}, multiple_locations: [{lat: latitude, lon: longitude}, {lat: 0, lon: 0}], aisle: aisle, details: details ) end def should_index? name != "DO NOT INDEX" end def search_name { name: name } end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/models/band.rb
test/models/band.rb
class Band searchkick end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/test/models/song.rb
test/models/song.rb
class Song searchkick def search_routing name end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/examples/semantic.rb
examples/semantic.rb
require "bundler/setup" require "active_record" require "elasticsearch" # or "opensearch-ruby" require "informers" require "searchkick" ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:" ActiveRecord::Schema.verbose = false ActiveRecord::Schema.define do create_table :products do |t| t.string :name t.json :embedding end end class Product < ActiveRecord::Base searchkick knn: {embedding: {dimensions: 768, distance: "cosine"}} end Product.reindex Product.create!(name: "Cereal") Product.create!(name: "Ice cream") Product.create!(name: "Eggs") embed = Informers.pipeline("embedding", "Snowflake/snowflake-arctic-embed-m-v1.5") embed_options = {model_output: "sentence_embedding", pooling: "none"} # specific to embedding model Product.find_each do |product| embedding = embed.(product.name, **embed_options) product.update!(embedding: embedding) end Product.search_index.refresh query = "breakfast" # the query prefix is specific to the embedding model (https://huggingface.co/Snowflake/snowflake-arctic-embed-m-v1.5) query_prefix = "Represent this sentence for searching relevant passages: " query_embedding = embed.(query_prefix + query, **embed_options) pp Product.search(knn: {field: :embedding, vector: query_embedding}, limit: 20).map(&:name)
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/examples/hybrid.rb
examples/hybrid.rb
require "bundler/setup" require "active_record" require "elasticsearch" # or "opensearch-ruby" require "informers" require "searchkick" ActiveRecord::Base.establish_connection adapter: "sqlite3", database: ":memory:" ActiveRecord::Schema.verbose = false ActiveRecord::Schema.define do create_table :products do |t| t.string :name t.json :embedding end end class Product < ActiveRecord::Base searchkick knn: {embedding: {dimensions: 768, distance: "cosine"}} end Product.reindex Product.create!(name: "Breakfast cereal") Product.create!(name: "Ice cream") Product.create!(name: "Eggs") embed = Informers.pipeline("embedding", "Snowflake/snowflake-arctic-embed-m-v1.5") embed_options = {model_output: "sentence_embedding", pooling: "none"} # specific to embedding model Product.find_each do |product| embedding = embed.(product.name, **embed_options) product.update!(embedding: embedding) end Product.search_index.refresh query = "breakfast" keyword_search = Product.search(query, limit: 20) # the query prefix is specific to the embedding model (https://huggingface.co/Snowflake/snowflake-arctic-embed-m-v1.5) query_prefix = "Represent this sentence for searching relevant passages: " query_embedding = embed.(query_prefix + query, **embed_options) semantic_search = Product.search(knn: {field: :embedding, vector: query_embedding}, limit: 20) Searchkick.multi_search([keyword_search, semantic_search]) # to combine the results, use Reciprocal Rank Fusion (RRF) p Searchkick::Reranking.rrf(keyword_search, semantic_search).first(5).map { |v| v[:result].name } # or a reranking model rerank = Informers.pipeline("reranking", "mixedbread-ai/mxbai-rerank-xsmall-v1") results = (keyword_search.to_a + semantic_search.to_a).uniq p rerank.(query, results.map(&:name)).first(5).map { |v| results[v[:doc_id]] }.map(&:name)
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick.rb
lib/searchkick.rb
# dependencies require "active_support" require "active_support/core_ext/hash/deep_merge" require "active_support/core_ext/module/attr_internal" require "active_support/core_ext/module/delegation" require "active_support/deprecation" require "active_support/log_subscriber" require "active_support/notifications" # stdlib require "forwardable" # modules require_relative "searchkick/controller_runtime" require_relative "searchkick/index" require_relative "searchkick/index_cache" require_relative "searchkick/index_options" require_relative "searchkick/indexer" require_relative "searchkick/hash_wrapper" require_relative "searchkick/log_subscriber" require_relative "searchkick/model" require_relative "searchkick/multi_search" require_relative "searchkick/query" require_relative "searchkick/reindex_queue" require_relative "searchkick/record_data" require_relative "searchkick/record_indexer" require_relative "searchkick/relation" require_relative "searchkick/relation_indexer" require_relative "searchkick/reranking" require_relative "searchkick/results" require_relative "searchkick/script" require_relative "searchkick/version" require_relative "searchkick/where" # integrations require_relative "searchkick/railtie" if defined?(Rails) module Searchkick # requires faraday autoload :Middleware, "searchkick/middleware" # background jobs autoload :BulkReindexJob, "searchkick/bulk_reindex_job" autoload :ProcessBatchJob, "searchkick/process_batch_job" autoload :ProcessQueueJob, "searchkick/process_queue_job" autoload :ReindexV2Job, "searchkick/reindex_v2_job" # errors class Error < StandardError; end class MissingIndexError < Error; end class UnsupportedVersionError < Error def message "This version of Searchkick requires Elasticsearch 8+ or OpenSearch 2+" end end class InvalidQueryError < Error; end class DangerousOperation < Error; end class ImportError < Error; end class << self attr_accessor :search_method_name, :timeout, :models, :client_options, :redis, :index_prefix, :index_suffix, :queue_name, :model_options, :client_type, :parent_job attr_writer :client, :env, :search_timeout attr_reader :aws_credentials end self.search_method_name = :search self.timeout = 10 self.models = [] self.client_options = {} self.queue_name = :searchkick self.model_options = {} self.parent_job = "ActiveJob::Base" def self.client @client ||= begin client_type = if self.client_type self.client_type elsif defined?(OpenSearch::Client) && defined?(Elasticsearch::Client) raise Error, "Multiple clients found - set Searchkick.client_type = :elasticsearch or :opensearch" elsif defined?(OpenSearch::Client) :opensearch elsif defined?(Elasticsearch::Client) :elasticsearch else raise Error, "No client found - install the `elasticsearch` or `opensearch-ruby` gem" end if client_type == :opensearch OpenSearch::Client.new({ url: ENV["OPENSEARCH_URL"], transport_options: {request: {timeout: timeout}}, retry_on_failure: 2 }.deep_merge(client_options)) do |f| f.use Searchkick::Middleware f.request :aws_sigv4, signer_middleware_aws_params if aws_credentials end else raise Error, "The `elasticsearch` gem must be 8+" if Elasticsearch::VERSION.to_i < 8 Elasticsearch::Client.new({ url: ENV["ELASTICSEARCH_URL"], transport_options: {request: {timeout: timeout}}, retry_on_failure: 2 }.deep_merge(client_options)) do |f| f.use Searchkick::Middleware f.request :aws_sigv4, signer_middleware_aws_params if aws_credentials end end end end def self.env @env ||= ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development" end def self.search_timeout (defined?(@search_timeout) && @search_timeout) || timeout end # private def self.server_info @server_info ||= client.info end def self.server_version @server_version ||= server_info["version"]["number"] end def self.opensearch? unless defined?(@opensearch) @opensearch = server_info["version"]["distribution"] == "opensearch" end @opensearch end def self.server_below?(version) Gem::Version.new(server_version.split("-")[0]) < Gem::Version.new(version.split("-")[0]) end # private def self.knn_support? if opensearch? !server_below?("2.4.0") else !server_below?("8.6.0") end end def self.search(term = "*", model: nil, **options, &block) options = options.dup klass = model # convert index_name into models if possible # this should allow for easier upgrade if options[:index_name] && !options[:models] && Array(options[:index_name]).all? { |v| v.respond_to?(:searchkick_index) } options[:models] = options.delete(:index_name) end # make Searchkick.search(models: [Product]) and Product.search equivalent unless klass models = Array(options[:models]) if models.size == 1 klass = models.first options.delete(:models) end end if klass if (options[:models] && Array(options[:models]) != [klass]) || Array(options[:index_name]).any? { |v| v.respond_to?(:searchkick_index) && v != klass } raise ArgumentError, "Use Searchkick.search to search multiple models" end end options = options.merge(block: block) if block Relation.new(klass, term, **options) end def self.multi_search(queries, opaque_id: nil) return if queries.empty? queries = queries.map { |q| q.send(:query) } event = { name: "Multi Search", body: queries.flat_map { |q| [q.params.except(:body).to_json, q.body.to_json] }.map { |v| "#{v}\n" }.join } ActiveSupport::Notifications.instrument("multi_search.searchkick", event) do MultiSearch.new(queries, opaque_id: opaque_id).perform end end # script # experimental def self.script(source, **options) Script.new(source, **options) end # callbacks def self.enable_callbacks self.callbacks_value = nil end def self.disable_callbacks self.callbacks_value = false end def self.callbacks?(default: true) if callbacks_value.nil? default else callbacks_value != false end end # message is private def self.callbacks(value = nil, message: nil) if block_given? previous_value = callbacks_value begin self.callbacks_value = value result = yield if callbacks_value == :bulk && indexer.queued_items.any? event = {} if message message.call(event) else event[:name] = "Bulk" event[:count] = indexer.queued_items.size end ActiveSupport::Notifications.instrument("request.searchkick", event) do indexer.perform end end result ensure self.callbacks_value = previous_value end else self.callbacks_value = value end end def self.aws_credentials=(creds) require "faraday_middleware/aws_sigv4" @aws_credentials = creds @client = nil # reset client end def self.reindex_status(index_name) raise Error, "Redis not configured" unless redis batches_left = Index.new(index_name).batches_left { completed: batches_left == 0, batches_left: batches_left } end def self.with_redis if redis if redis.respond_to?(:with) redis.with do |r| yield r end else yield redis end end end def self.warn(message) super("[searchkick] WARNING: #{message}") end # private def self.load_records(relation, ids) relation = if relation.respond_to?(:primary_key) primary_key = relation.primary_key raise Error, "Need primary key to load records" if !primary_key relation.where(primary_key => ids) elsif relation.respond_to?(:queryable) relation.queryable.for_ids(ids) end raise Error, "Not sure how to load records" if !relation relation end # public (for reindexing conversions) def self.load_model(class_name, allow_child: false) model = class_name.safe_constantize raise Error, "Could not find class: #{class_name}" unless model if allow_child unless model.respond_to?(:searchkick_klass) raise Error, "#{class_name} is not a searchkick model" end else unless Searchkick.models.include?(model) raise Error, "#{class_name} is not a searchkick model" end end model end # private def self.indexer Thread.current[:searchkick_indexer] ||= Indexer.new end # private def self.callbacks_value Thread.current[:searchkick_callbacks_enabled] end # private def self.callbacks_value=(value) Thread.current[:searchkick_callbacks_enabled] = value end # private def self.signer_middleware_aws_params {service: "es", region: "us-east-1"}.merge(aws_credentials) end # private # methods are forwarded to base class # this check to see if scope exists on that class # it's a bit tricky, but this seems to work def self.relation?(klass) if klass.respond_to?(:current_scope) !klass.current_scope.nil? else klass.is_a?(Mongoid::Criteria) || !Mongoid::Threaded.current_scope(klass).nil? end end # private def self.scope(model) # safety check to make sure used properly in code raise Error, "Cannot scope relation" if relation?(model) if model.searchkick_options[:unscope] model.unscoped else model end end # private def self.not_found_error?(e) (defined?(Elastic::Transport) && e.is_a?(Elastic::Transport::Transport::Errors::NotFound)) || (defined?(Elasticsearch::Transport) && e.is_a?(Elasticsearch::Transport::Transport::Errors::NotFound)) || (defined?(OpenSearch) && e.is_a?(OpenSearch::Transport::Transport::Errors::NotFound)) end # private def self.transport_error?(e) (defined?(Elastic::Transport) && e.is_a?(Elastic::Transport::Transport::Error)) || (defined?(Elasticsearch::Transport) && e.is_a?(Elasticsearch::Transport::Transport::Error)) || (defined?(OpenSearch) && e.is_a?(OpenSearch::Transport::Transport::Error)) end # private def self.not_allowed_error?(e) (defined?(Elastic::Transport) && e.is_a?(Elastic::Transport::Transport::Errors::MethodNotAllowed)) || (defined?(Elasticsearch::Transport) && e.is_a?(Elasticsearch::Transport::Transport::Errors::MethodNotAllowed)) || (defined?(OpenSearch) && e.is_a?(OpenSearch::Transport::Transport::Errors::MethodNotAllowed)) end end ActiveSupport.on_load(:active_record) do extend Searchkick::Model end ActiveSupport.on_load(:mongoid) do Mongoid::Document::ClassMethods.include Searchkick::Model end ActiveSupport.on_load(:action_controller) do include Searchkick::ControllerRuntime end Searchkick::LogSubscriber.attach_to :searchkick
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/record_data.rb
lib/searchkick/record_data.rb
module Searchkick class RecordData TYPE_KEYS = ["type", :type] attr_reader :index, :record def initialize(index, record) @index = index @record = record end def index_data data = record_data data[:data] = search_data {index: data} end def update_data(method_name) data = record_data data[:data] = {doc: search_data(method_name)} {update: data} end def delete_data {delete: record_data} end # custom id can be useful for load: false def search_id id = record.respond_to?(:search_document_id) ? record.search_document_id : record.id id.is_a?(Numeric) ? id : id.to_s end def document_type(ignore_type = false) index.klass_document_type(record.class, ignore_type) end def record_data data = { _index: index.name, _id: search_id } data[:routing] = record.search_routing if record.respond_to?(:search_routing) data end private def search_data(method_name = nil) partial_reindex = !method_name.nil? source = record.send(method_name || :search_data) # conversions index.conversions_fields.each do |conversions_field| if source[conversions_field] source[conversions_field] = source[conversions_field].map { |k, v| {query: k, count: v} } end end index.conversions_v2_fields.each do |conversions_field| key = source.key?(conversions_field) ? conversions_field : conversions_field.to_sym if !partial_reindex || source[key] if index.options[:case_sensitive] source[key] = (source[key] || {}).reduce(Hash.new(0)) do |memo, (k, v)| memo[k.to_s.gsub(".", "*")] += v memo end else source[key] = (source[key] || {}).reduce(Hash.new(0)) do |memo, (k, v)| memo[k.to_s.downcase.gsub(".", "*")] += v memo end end end end # hack to prevent generator field doesn't exist error if !partial_reindex index.suggest_fields.each do |field| if !source.key?(field) && !source.key?(field.to_sym) source[field] = nil end end end # locations index.locations_fields.each do |field| if source[field] if !source[field].is_a?(Hash) && (source[field].first.is_a?(Array) || source[field].first.is_a?(Hash)) # multiple locations source[field] = source[field].map { |a| location_value(a) } else source[field] = location_value(source[field]) end end end if index.options[:inheritance] if !TYPE_KEYS.any? { |tk| source.key?(tk) } source[:type] = document_type(true) end end cast_big_decimal(source) source end def location_value(value) if value.is_a?(Array) value.map(&:to_f).reverse elsif value.is_a?(Hash) {lat: value[:lat].to_f, lon: value[:lon].to_f} else value end end # change all BigDecimal values to floats due to # https://github.com/rails/rails/issues/6033 # possible loss of precision :/ def cast_big_decimal(obj) case obj when BigDecimal obj.to_f when Hash obj.each do |k, v| # performance if v.is_a?(BigDecimal) obj[k] = v.to_f elsif v.is_a?(Enumerable) obj[k] = cast_big_decimal(v) end end when Enumerable obj.map do |v| cast_big_decimal(v) end else obj end end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/script.rb
lib/searchkick/script.rb
module Searchkick class Script attr_reader :source, :lang, :params def initialize(source, lang: "painless", params: {}) @source = source @lang = lang @params = params end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/version.rb
lib/searchkick/version.rb
module Searchkick VERSION = "6.0.2" end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/index_cache.rb
lib/searchkick/index_cache.rb
module Searchkick class IndexCache def initialize(max_size: 20) @data = {} @mutex = Mutex.new @max_size = max_size end # probably a better pattern for this # but keep it simple def fetch(name) # thread-safe in MRI without mutex # due to how context switching works @mutex.synchronize do if @data.key?(name) @data[name] else @data.clear if @data.size >= @max_size @data[name] = yield end end end def clear @mutex.synchronize do @data.clear end end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/reindex_queue.rb
lib/searchkick/reindex_queue.rb
module Searchkick class ReindexQueue attr_reader :name def initialize(name) @name = name raise Error, "Searchkick.redis not set" unless Searchkick.redis end # supports single and multiple ids def push(record_ids) Searchkick.with_redis { |r| r.call("LPUSH", redis_key, record_ids) } end def push_records(records) record_ids = records.map do |record| # always pass routing in case record is deleted # before the queue job runs if record.respond_to?(:search_routing) routing = record.search_routing end # escape pipe with double pipe value = escape(record.id.to_s) value = "#{value}|#{escape(routing)}" if routing value end push(record_ids) end # TODO use reliable queuing def reserve(limit: 1000) Searchkick.with_redis { |r| r.call("RPOP", redis_key, limit) }.to_a end def clear Searchkick.with_redis { |r| r.call("DEL", redis_key) } end def length Searchkick.with_redis { |r| r.call("LLEN", redis_key) } end private def redis_key "searchkick:reindex_queue:#{name}" end def escape(value) value.to_s.gsub("|", "||") end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/log_subscriber.rb
lib/searchkick/log_subscriber.rb
# based on https://gist.github.com/mnutt/566725 module Searchkick class LogSubscriber < ActiveSupport::LogSubscriber def self.runtime=(value) Thread.current[:searchkick_runtime] = value end def self.runtime Thread.current[:searchkick_runtime] ||= 0 end def self.reset_runtime rt = runtime self.runtime = 0 rt end def search(event) self.class.runtime += event.duration return unless logger.debug? payload = event.payload name = "#{payload[:name]} (#{event.duration.round(1)}ms)" index = payload[:query][:index].is_a?(Array) ? payload[:query][:index].join(",") : payload[:query][:index] type = payload[:query][:type] request_params = payload[:query].except(:index, :type, :body, :opaque_id) params = [] request_params.each do |k, v| params << "#{CGI.escape(k.to_s)}=#{CGI.escape(v.to_s)}" end debug " #{color(name, YELLOW, bold: true)} #{index}#{type ? "/#{type.join(',')}" : ''}/_search#{params.any? ? '?' + params.join('&') : nil} #{payload[:query][:body].to_json}" end def request(event) self.class.runtime += event.duration return unless logger.debug? payload = event.payload name = "#{payload[:name]} (#{event.duration.round(1)}ms)" debug " #{color(name, YELLOW, bold: true)} #{payload.except(:name).to_json}" end def multi_search(event) self.class.runtime += event.duration return unless logger.debug? payload = event.payload name = "#{payload[:name]} (#{event.duration.round(1)}ms)" debug " #{color(name, YELLOW, bold: true)} _msearch #{payload[:body]}" end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/middleware.rb
lib/searchkick/middleware.rb
require "faraday" module Searchkick class Middleware < Faraday::Middleware def call(env) path = env[:url].path.to_s if path.end_with?("/_search") env[:request][:timeout] = Searchkick.search_timeout elsif path.end_with?("/_msearch") # assume no concurrent searches for timeout for now searches = env[:request_body].count("\n") / 2 # do not allow timeout to exceed Searchkick.timeout timeout = [Searchkick.search_timeout * searches, Searchkick.timeout].min env[:request][:timeout] = timeout end @app.call(env) end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/controller_runtime.rb
lib/searchkick/controller_runtime.rb
# based on https://gist.github.com/mnutt/566725 module Searchkick module ControllerRuntime extend ActiveSupport::Concern protected attr_internal :searchkick_runtime def process_action(action, *args) # We also need to reset the runtime before each action # because of queries in middleware or in cases we are streaming # and it won't be cleaned up by the method below. Searchkick::LogSubscriber.reset_runtime super end def cleanup_view_runtime searchkick_rt_before_render = Searchkick::LogSubscriber.reset_runtime runtime = super searchkick_rt_after_render = Searchkick::LogSubscriber.reset_runtime self.searchkick_runtime = searchkick_rt_before_render + searchkick_rt_after_render runtime - searchkick_rt_after_render end def append_info_to_payload(payload) super payload[:searchkick_runtime] = (searchkick_runtime || 0) + Searchkick::LogSubscriber.reset_runtime end module ClassMethods def log_process_action(payload) messages = super runtime = payload[:searchkick_runtime] messages << ("Searchkick: %.1fms" % runtime.to_f) if runtime.to_f > 0 messages end end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/hash_wrapper.rb
lib/searchkick/hash_wrapper.rb
module Searchkick class HashWrapper def initialize(attributes) @attributes = attributes end def [](name) @attributes[name.to_s] end def to_h @attributes end def as_json(...) @attributes.as_json(...) end def to_json(...) @attributes.to_json(...) end def method_missing(name, ...) if @attributes.key?(name.to_s) self[name] else super end end def respond_to_missing?(name, ...) @attributes.key?(name.to_s) || super end def inspect attributes = @attributes.reject { |k, v| k[0] == "_" }.map { |k, v| "#{k}: #{v.inspect}" } attributes.unshift(attributes.pop) # move id to start "#<#{self.class.name} #{attributes.join(", ")}>" end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/index.rb
lib/searchkick/index.rb
module Searchkick class Index attr_reader :name, :options def initialize(name, options = {}) @name = name @options = options @klass_document_type = {} # cache end def index_options IndexOptions.new(self).index_options end def create(body = {}) client.indices.create index: name, body: body end def delete if alias_exists? # can't call delete directly on aliases in ES 6 indices = client.indices.get_alias(name: name).keys client.indices.delete index: indices else client.indices.delete index: name end end def exists? client.indices.exists index: name end def refresh client.indices.refresh index: name end def alias_exists? client.indices.exists_alias name: name end # call to_h for consistent results between elasticsearch gem 7 and 8 # could do for all API calls, but just do for ones where return value is focus for now def mapping client.indices.get_mapping(index: name).to_h end # call to_h for consistent results between elasticsearch gem 7 and 8 def settings client.indices.get_settings(index: name).to_h end def refresh_interval index_settings["refresh_interval"] end def update_settings(settings) client.indices.put_settings index: name, body: settings end def tokens(text, options = {}) client.indices.analyze(body: {text: text}.merge(options), index: name)["tokens"].map { |t| t["token"] } end def total_docs response = client.search( index: name, body: { query: {match_all: {}}, size: 0, track_total_hits: true } ) Results.new(nil, response).total_count end def promote(new_name, update_refresh_interval: false) if update_refresh_interval new_index = Index.new(new_name, @options) settings = options[:settings] || {} refresh_interval = (settings[:index] && settings[:index][:refresh_interval]) || "1s" new_index.update_settings(index: {refresh_interval: refresh_interval}) end old_indices = begin client.indices.get_alias(name: name).keys rescue => e raise e unless Searchkick.not_found_error?(e) {} end actions = old_indices.map { |old_name| {remove: {index: old_name, alias: name}} } + [{add: {index: new_name, alias: name}}] client.indices.update_aliases body: {actions: actions} end alias_method :swap, :promote def retrieve(record) record_data = RecordData.new(self, record).record_data # remove underscore get_options = record_data.to_h { |k, v| [k.to_s.delete_prefix("_").to_sym, v] } client.get(get_options)["_source"] end def all_indices(unaliased: false) indices = begin if client.indices.respond_to?(:get_alias) client.indices.get_alias(index: "#{name}*") else client.indices.get_aliases end rescue => e raise e unless Searchkick.not_found_error?(e) {} end indices = indices.select { |_k, v| v.empty? || v["aliases"].empty? } if unaliased indices.select { |k, _v| k =~ /\A#{Regexp.escape(name)}_\d{14,17}\z/ }.keys end # remove old indices that start w/ index_name def clean_indices indices = all_indices(unaliased: true) indices.each do |index| Index.new(index).delete end indices end def store(record) notify(record, "Store") do queue_index([record]) end end def remove(record) notify(record, "Remove") do queue_delete([record]) end end def update_record(record, method_name) notify(record, "Update") do queue_update([record], method_name) end end def bulk_delete(records) return if records.empty? notify_bulk(records, "Delete") do queue_delete(records) end end def bulk_index(records) return if records.empty? notify_bulk(records, "Import") do queue_index(records) end end alias_method :import, :bulk_index def bulk_update(records, method_name, ignore_missing: nil) return if records.empty? notify_bulk(records, "Update") do queue_update(records, method_name, ignore_missing: ignore_missing) end end def search_id(record) RecordData.new(self, record).search_id end def document_type(record) RecordData.new(self, record).document_type end def similar_record(record, **options) options[:per_page] ||= 10 options[:similar] = [RecordData.new(self, record).record_data] options[:models] ||= [record.class] unless options.key?(:model) Searchkick.search("*", **options) end def reload_synonyms if Searchkick.opensearch? client.transport.perform_request "POST", "_plugins/_refresh_search_analyzers/#{CGI.escape(name)}" else begin client.transport.perform_request("GET", "#{CGI.escape(name)}/_reload_search_analyzers") rescue => e raise Error, "Requires non-OSS version of Elasticsearch" if Searchkick.not_allowed_error?(e) raise e end end end # queue def reindex_queue ReindexQueue.new(name) end # reindex # note: this is designed to be used internally # so it does not check object matches index class def reindex(object, method_name: nil, ignore_missing: nil, full: false, **options) if @options[:job_options] options[:job_options] = (@options[:job_options] || {}).merge(options[:job_options] || {}) end if object.is_a?(Array) # note: purposefully skip full return reindex_records(object, method_name: method_name, ignore_missing: ignore_missing, **options) end if !object.respond_to?(:searchkick_klass) raise Error, "Cannot reindex object" end scoped = Searchkick.relation?(object) # call searchkick_klass for inheritance relation = scoped ? object.all : Searchkick.scope(object.searchkick_klass).all refresh = options.fetch(:refresh, !scoped) options.delete(:refresh) if method_name || (scoped && !full) mode = options.delete(:mode) || :inline scope = options.delete(:scope) job_options = options.delete(:job_options) raise ArgumentError, "unsupported keywords: #{options.keys.map(&:inspect).join(", ")}" if options.any? # import only import_scope(relation, method_name: method_name, mode: mode, scope: scope, ignore_missing: ignore_missing, job_options: job_options) self.refresh if refresh true else async = options.delete(:async) if async if async.is_a?(Hash) && async[:wait] Searchkick.warn "async option is deprecated - use mode: :async, wait: true instead" options[:wait] = true unless options.key?(:wait) else Searchkick.warn "async option is deprecated - use mode: :async instead" end options[:mode] ||= :async end full_reindex(relation, **options) end end def create_index(index_options: nil) index_options ||= self.index_options index = Index.new("#{name}_#{Time.now.strftime('%Y%m%d%H%M%S%L')}", @options) index.create(index_options) index end def import_scope(relation, **options) relation_indexer.reindex(relation, **options) end def batches_left relation_indexer.batches_left end # private def klass_document_type(klass, ignore_type = false) @klass_document_type[[klass, ignore_type]] ||= begin if !ignore_type && klass.searchkick_klass.searchkick_options[:_type] type = klass.searchkick_klass.searchkick_options[:_type] type = type.call if type.respond_to?(:call) type else klass.model_name.to_s.underscore end end end # private def conversions_fields @conversions_fields ||= begin conversions = Array(options[:conversions]) conversions.map(&:to_s) + conversions.map(&:to_sym) end end # private def conversions_v2_fields @conversions_v2_fields ||= Array(options[:conversions_v2]).map(&:to_s) end # private def suggest_fields @suggest_fields ||= Array(options[:suggest]).map(&:to_s) end # private def locations_fields @locations_fields ||= begin locations = Array(options[:locations]) locations.map(&:to_s) + locations.map(&:to_sym) end end # private def uuid index_settings["uuid"] end protected def client Searchkick.client end def queue_index(records) Searchkick.indexer.queue(records.map { |r| RecordData.new(self, r).index_data }) end def queue_delete(records) Searchkick.indexer.queue(records.reject { |r| r.id.blank? }.map { |r| RecordData.new(self, r).delete_data }) end def queue_update(records, method_name, ignore_missing:) items = records.map { |r| RecordData.new(self, r).update_data(method_name) } items.each { |i| i.instance_variable_set(:@ignore_missing, true) } if ignore_missing Searchkick.indexer.queue(items) end def relation_indexer @relation_indexer ||= RelationIndexer.new(self) end def index_settings settings.values.first["settings"]["index"] end def import_before_promotion(index, relation, **import_options) index.import_scope(relation, **import_options) end def reindex_records(object, mode: nil, refresh: false, **options) mode ||= Searchkick.callbacks_value || @options[:callbacks] || :inline mode = :inline if mode == :bulk result = RecordIndexer.new(self).reindex(object, mode: mode, full: false, **options) self.refresh if refresh result end # https://gist.github.com/jarosan/3124884 # https://www.elastic.co/blog/changing-mapping-with-zero-downtime/ def full_reindex(relation, import: true, resume: false, retain: false, mode: nil, refresh_interval: nil, scope: nil, wait: nil, job_options: nil) raise ArgumentError, "wait only available in :async mode" if !wait.nil? && mode != :async raise ArgumentError, "Full reindex does not support :queue mode - use :async mode instead" if mode == :queue if resume index_name = all_indices.sort.last raise Error, "No index to resume" unless index_name index = Index.new(index_name, @options) else clean_indices unless retain index_options = relation.searchkick_index_options index_options.deep_merge!(settings: {index: {refresh_interval: refresh_interval}}) if refresh_interval index = create_index(index_options: index_options) end import_options = { mode: (mode || :inline), full: true, resume: resume, scope: scope, job_options: job_options } uuid = index.uuid # check if alias exists alias_exists = alias_exists? if alias_exists import_before_promotion(index, relation, **import_options) if import # get existing indices to remove unless mode == :async check_uuid(uuid, index.uuid) promote(index.name, update_refresh_interval: !refresh_interval.nil?) clean_indices unless retain end else delete if exists? promote(index.name, update_refresh_interval: !refresh_interval.nil?) # import after promotion index.import_scope(relation, **import_options) if import end if mode == :async if wait puts "Created index: #{index.name}" puts "Jobs queued. Waiting..." loop do sleep 3 status = Searchkick.reindex_status(index.name) break if status[:completed] puts "Batches left: #{status[:batches_left]}" end # already promoted if alias didn't exist if alias_exists puts "Jobs complete. Promoting..." check_uuid(uuid, index.uuid) promote(index.name, update_refresh_interval: !refresh_interval.nil?) end clean_indices unless retain puts "SUCCESS!" end {index_name: index.name} else index.refresh true end rescue => e if Searchkick.transport_error?(e) && (e.message.include?("No handler for type [text]") || e.message.include?("class java.util.ArrayList cannot be cast to class java.util.Map")) raise UnsupportedVersionError end raise e end # safety check # still a chance for race condition since its called before promotion # ideal is for user to disable automatic index creation # https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#index-creation def check_uuid(old_uuid, new_uuid) if old_uuid != new_uuid raise Error, "Safety check failed - only run one Model.reindex per model at a time" end end def notify(record, name) if Searchkick.callbacks_value == :bulk yield else name = "#{record.class.searchkick_klass.name} #{name}" if record && record.class.searchkick_klass event = { name: name, id: search_id(record) } ActiveSupport::Notifications.instrument("request.searchkick", event) do yield end end end def notify_bulk(records, name) if Searchkick.callbacks_value == :bulk yield else event = { name: "#{records.first.class.searchkick_klass.name} #{name}", count: records.size } ActiveSupport::Notifications.instrument("request.searchkick", event) do yield end end end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/process_queue_job.rb
lib/searchkick/process_queue_job.rb
module Searchkick class ProcessQueueJob < Searchkick.parent_job.constantize queue_as { Searchkick.queue_name } def perform(class_name:, index_name: nil, inline: false, job_options: nil) model = Searchkick.load_model(class_name) index = model.searchkick_index(name: index_name) limit = model.searchkick_options[:batch_size] || 1000 job_options = (model.searchkick_options[:job_options] || {}).merge(job_options || {}) loop do record_ids = index.reindex_queue.reserve(limit: limit) if record_ids.any? batch_options = { class_name: class_name, record_ids: record_ids.uniq, index_name: index_name } if inline # use new.perform to avoid excessive logging Searchkick::ProcessBatchJob.new.perform(**batch_options) else Searchkick::ProcessBatchJob.set(job_options).perform_later(**batch_options) end # TODO when moving to reliable queuing, mark as complete end break unless record_ids.size == limit end end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/record_indexer.rb
lib/searchkick/record_indexer.rb
module Searchkick class RecordIndexer attr_reader :index def initialize(index) @index = index end def reindex(records, mode:, method_name:, ignore_missing:, full: false, single: false, job_options: nil) # prevents exists? check if records is a relation records = records.to_a return if records.empty? case mode when :async unless defined?(ActiveJob) raise Error, "Active Job not found" end job_options ||= {} # only add if set for backwards compatibility extra_options = {} if ignore_missing extra_options[:ignore_missing] = ignore_missing end # we could likely combine ReindexV2Job, BulkReindexJob, and ProcessBatchJob # but keep them separate for now if single record = records.first # always pass routing in case record is deleted # before the async job runs if record.respond_to?(:search_routing) routing = record.search_routing end Searchkick::ReindexV2Job.set(**job_options).perform_later( record.class.name, record.id.to_s, method_name ? method_name.to_s : nil, routing: routing, index_name: index.name, **extra_options ) else Searchkick::BulkReindexJob.set(**job_options).perform_later( class_name: records.first.class.searchkick_options[:class_name], record_ids: records.map { |r| r.id.to_s }, index_name: index.name, method_name: method_name ? method_name.to_s : nil, **extra_options ) end when :queue if method_name raise Error, "Partial reindex not supported with queue option" end index.reindex_queue.push_records(records) when true, :inline index_records, other_records = records.partition { |r| index_record?(r) } import_inline(index_records, !full ? other_records : [], method_name: method_name, ignore_missing: ignore_missing, single: single) else raise ArgumentError, "Invalid value for mode" end # return true like model and relation reindex for now true end def reindex_items(klass, items, method_name:, ignore_missing:, single: false) routing = items.to_h { |r| [r[:id], r[:routing]] } record_ids = routing.keys relation = Searchkick.load_records(klass, record_ids) # call search_import even for single records for nested associations relation = relation.search_import if relation.respond_to?(:search_import) records = relation.select(&:should_index?) # determine which records to delete delete_ids = record_ids - records.map { |r| r.id.to_s } delete_records = delete_ids.map do |id| construct_record(klass, id, routing[id]) end import_inline(records, delete_records, method_name: method_name, ignore_missing: ignore_missing, single: single) end private def index_record?(record) record.persisted? && !record.destroyed? && record.should_index? end # import in single request with retries def import_inline(index_records, delete_records, method_name:, ignore_missing:, single:) return if index_records.empty? && delete_records.empty? maybe_bulk(index_records, delete_records, method_name, single) do if index_records.any? if method_name index.bulk_update(index_records, method_name, ignore_missing: ignore_missing) else index.bulk_index(index_records) end end if delete_records.any? index.bulk_delete(delete_records) end end end def maybe_bulk(index_records, delete_records, method_name, single) if Searchkick.callbacks_value == :bulk yield else # set action and data action = if single && index_records.empty? "Remove" elsif method_name "Update" else single ? "Store" : "Import" end record = index_records.first || delete_records.first name = record.class.searchkick_klass.name message = lambda do |event| event[:name] = "#{name} #{action}" if single event[:id] = index.search_id(record) else event[:count] = index_records.size + delete_records.size end end with_retries do Searchkick.callbacks(:bulk, message: message) do yield end end end end def construct_record(klass, id, routing) record = klass.new record.id = id if routing record.define_singleton_method(:search_routing) do routing end end record end def with_retries retries = 0 begin yield rescue Faraday::ClientError => e if retries < 1 retries += 1 retry end raise e end end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/query.rb
lib/searchkick/query.rb
module Searchkick class Query include Enumerable extend Forwardable @@metric_aggs = [:avg, :cardinality, :max, :min, :sum] attr_reader :klass, :term, :options attr_accessor :body def_delegators :execute, :map, :each, :any?, :empty?, :size, :length, :slice, :[], :to_ary, :results, :suggestions, :each_with_hit, :with_details, :aggregations, :aggs, :took, :error, :model_name, :entry_name, :total_count, :total_entries, :current_page, :per_page, :limit_value, :padding, :total_pages, :num_pages, :offset_value, :offset, :previous_page, :prev_page, :next_page, :first_page?, :last_page?, :out_of_range?, :hits, :response, :to_a, :first, :scroll, :highlights, :with_highlights, :with_score, :misspellings?, :scroll_id, :clear_scroll, :missing_records, :with_hit def initialize(klass, term = "*", **options) if options[:conversions] Searchkick.warn("The `conversions` option is deprecated in favor of `conversions_v2`, which provides much better search performance. Upgrade to `conversions_v2` or rename `conversions` to `conversions_v1`") end if options.key?(:conversions_v1) options[:conversions] = options.delete(:conversions_v1) end unknown_keywords = options.keys - [:aggs, :block, :body, :body_options, :boost, :boost_by, :boost_by_distance, :boost_by_recency, :boost_where, :conversions, :conversions_v2, :conversions_term, :debug, :emoji, :exclude, :explain, :fields, :highlight, :includes, :index_name, :indices_boost, :knn, :limit, :load, :match, :misspellings, :models, :model_includes, :offset, :opaque_id, :operator, :order, :padding, :page, :per_page, :profile, :request_params, :routing, :scope_results, :scroll, :select, :similar, :smart_aggs, :suggest, :total_entries, :track, :type, :where] raise ArgumentError, "unknown keywords: #{unknown_keywords.join(", ")}" if unknown_keywords.any? term = term.to_s if options[:emoji] term = EmojiParser.parse_unicode(term) { |e| " #{e.name.tr('_', ' ')} " }.strip end @klass = klass @term = term @options = options @match_suffix = options[:match] || searchkick_options[:match] || "analyzed" # prevent Ruby warnings @type = nil @routing = nil @misspellings = false @misspellings_below = nil @highlighted_fields = nil @index_mapping = nil prepare end def searchkick_index klass ? klass.searchkick_index : nil end def searchkick_options klass ? klass.searchkick_options : {} end def searchkick_klass klass ? klass.searchkick_klass : nil end def params if options[:models] @index_mapping = {} Array(options[:models]).each do |model| # there can be multiple models per index name due to inheritance - see #1259 (@index_mapping[model.searchkick_index.name] ||= []) << model end end index = if options[:index_name] Array(options[:index_name]).map { |v| v.respond_to?(:searchkick_index) ? v.searchkick_index.name : v }.join(",") elsif options[:models] @index_mapping.keys.join(",") elsif searchkick_index searchkick_index.name else # fixes warning about accessing system indices "*,-.*" end params = { index: index, body: body } params[:type] = @type if @type params[:routing] = @routing if @routing params[:scroll] = @scroll if @scroll params[:opaque_id] = @opaque_id if @opaque_id params.merge!(options[:request_params]) if options[:request_params] params end def execute @execute ||= begin begin response = execute_search if retry_misspellings?(response) prepare response = execute_search end rescue => e handle_error(e) end handle_response(response) end end def handle_response(response) opts = { page: @page, per_page: @per_page, padding: @padding, load: @load, includes: options[:includes], model_includes: options[:model_includes], json: !@json.nil?, match_suffix: @match_suffix, highlight: options[:highlight], highlighted_fields: @highlighted_fields || [], misspellings: @misspellings, term: term, scope_results: options[:scope_results], total_entries: options[:total_entries], index_mapping: @index_mapping, suggest: options[:suggest], scroll: options[:scroll], opaque_id: options[:opaque_id] } if options[:debug] server = Searchkick.opensearch? ? "OpenSearch" : "Elasticsearch" puts "Searchkick #{Searchkick::VERSION}" puts "#{server} #{Searchkick.server_version}" puts puts "Model Options" pp searchkick_options puts puts "Search Options" pp options puts if searchkick_index puts "Record Data" begin pp klass.limit(3).map { |r| RecordData.new(searchkick_index, r).index_data } rescue => e puts "#{e.class.name}: #{e.message}" end puts puts "Mapping" puts JSON.pretty_generate(searchkick_index.mapping) puts puts "Settings" puts JSON.pretty_generate(searchkick_index.settings) puts end puts "Query" puts JSON.pretty_generate(params[:body]) puts puts "Results" puts JSON.pretty_generate(response.to_h) end # set execute for multi search @execute = Results.new(searchkick_klass, response, opts) end def retry_misspellings?(response) @misspellings_below && response["error"].nil? && Results.new(searchkick_klass, response).total_count < @misspellings_below end private def handle_error(e) status_code = e.message[1..3].to_i if status_code == 404 if e.message.include?("No search context found for id") raise MissingIndexError, "No search context found for id" else raise MissingIndexError, "Index missing - run #{reindex_command}" end elsif status_code == 500 && ( e.message.include?("IllegalArgumentException[minimumSimilarity >= 1]") || e.message.include?("No query registered for [multi_match]") || e.message.include?("[match] query does not support [cutoff_frequency]") || e.message.include?("No query registered for [function_score]") ) raise UnsupportedVersionError elsif status_code == 400 if ( e.message.include?("bool query does not support [filter]") || e.message.include?("[bool] filter does not support [filter]") ) raise UnsupportedVersionError elsif e.message.match?(/analyzer \[searchkick_.+\] not found/) raise InvalidQueryError, "Bad mapping - run #{reindex_command}" else raise InvalidQueryError, e.message end else raise e end end def reindex_command searchkick_klass ? "#{searchkick_klass.name}.reindex" : "reindex" end def execute_search name = searchkick_klass ? "#{searchkick_klass.name} Search" : "Search" event = { name: name, query: params } ActiveSupport::Notifications.instrument("search.searchkick", event) do Searchkick.client.search(params) end end def prepare boost_fields, fields = set_fields operator = options[:operator] || "and" # pagination page = [options[:page].to_i, 1].max # maybe use index.max_result_window in the future default_limit = searchkick_options[:deep_paging] ? 1_000_000_000 : 10_000 per_page = (options[:limit] || options[:per_page] || default_limit).to_i padding = [options[:padding].to_i, 0].max offset = (options[:offset] || (page - 1) * per_page + padding).to_i scroll = options[:scroll] opaque_id = options[:opaque_id] max_result_window = searchkick_options[:max_result_window] original_per_page = per_page if max_result_window offset = max_result_window if offset > max_result_window per_page = max_result_window - offset if offset + per_page > max_result_window end # model and eager loading load = options[:load].nil? ? true : options[:load] all = term == "*" @json = options[:body] if @json ignored_options = options.keys & [:aggs, :boost, :boost_by, :boost_by_distance, :boost_by_recency, :boost_where, :conversions, :conversions_term, :exclude, :explain, :fields, :highlight, :indices_boost, :match, :misspellings, :operator, :order, :profile, :select, :smart_aggs, :suggest, :where] raise ArgumentError, "Options incompatible with body option: #{ignored_options.join(", ")}" if ignored_options.any? payload = @json else must_not = [] should = [] if options[:similar] like = options[:similar] == true ? term : options[:similar] query = { more_like_this: { like: like, min_doc_freq: 1, min_term_freq: 1, analyzer: "searchkick_search2" } } if fields.all? { |f| f.start_with?("*.") } raise ArgumentError, "Must specify fields to search" end if fields != ["_all"] query[:more_like_this][:fields] = fields end elsif all && !options[:exclude] query = { match_all: {} } else queries = [] misspellings = if options.key?(:misspellings) options[:misspellings] else true end if misspellings.is_a?(Hash) && misspellings[:below] && !@misspellings_below @misspellings_below = misspellings[:below].to_i misspellings = false end if misspellings != false edit_distance = (misspellings.is_a?(Hash) && (misspellings[:edit_distance] || misspellings[:distance])) || 1 transpositions = if misspellings.is_a?(Hash) && misspellings.key?(:transpositions) {fuzzy_transpositions: misspellings[:transpositions]} else {fuzzy_transpositions: true} end prefix_length = (misspellings.is_a?(Hash) && misspellings[:prefix_length]) || 0 default_max_expansions = @misspellings_below ? 20 : 3 max_expansions = (misspellings.is_a?(Hash) && misspellings[:max_expansions]) || default_max_expansions misspellings_fields = misspellings.is_a?(Hash) && misspellings.key?(:fields) && misspellings[:fields].map(&:to_s) if misspellings_fields missing_fields = misspellings_fields - fields.map { |f| base_field(f) } if missing_fields.any? raise ArgumentError, "All fields in per-field misspellings must also be specified in fields option" end end @misspellings = true else @misspellings = false end fields.each do |field| queries_to_add = [] qs = [] factor = boost_fields[field] || 1 shared_options = { query: term, boost: 10 * factor } match_type = if field.end_with?(".phrase") field = if field == "_all.phrase" "_all" else field.sub(/\.phrase\z/, ".analyzed") end :match_phrase else :match end shared_options[:operator] = operator if match_type == :match exclude_analyzer = nil exclude_field = field field_misspellings = misspellings && (!misspellings_fields || misspellings_fields.include?(base_field(field))) if field == "_all" || field.end_with?(".analyzed") qs << shared_options.merge(analyzer: "searchkick_search") # searchkick_search and searchkick_search2 are the same for some languages unless %w(japanese japanese2 korean polish ukrainian vietnamese).include?(searchkick_options[:language]) qs << shared_options.merge(analyzer: "searchkick_search2") end exclude_analyzer = "searchkick_search2" elsif field.end_with?(".exact") f = field.split(".")[0..-2].join(".") queries_to_add << {match: {f => shared_options.merge(analyzer: "keyword")}} exclude_field = f exclude_analyzer = "keyword" else analyzer = field.match?(/\.word_(start|middle|end)\z/) ? "searchkick_word_search" : "searchkick_autocomplete_search" qs << shared_options.merge(analyzer: analyzer) exclude_analyzer = analyzer end if field_misspellings != false && match_type == :match qs.concat(qs.map { |q| q.except(:cutoff_frequency).merge(fuzziness: edit_distance, prefix_length: prefix_length, max_expansions: max_expansions, boost: factor).merge(transpositions) }) end if field.start_with?("*.") q2 = qs.map { |q| {multi_match: q.merge(fields: [field], type: match_type == :match_phrase ? "phrase" : "best_fields")} } else q2 = qs.map { |q| {match_type => {field => q}} } end # boost exact matches more if field =~ /\.word_(start|middle|end)\z/ && searchkick_options[:word] != false queries_to_add << { bool: { must: { bool: { should: q2 } }, should: {match_type => {field.sub(/\.word_(start|middle|end)\z/, ".analyzed") => qs.first}} } } else queries_to_add.concat(q2) end queries << queries_to_add if options[:exclude] must_not.concat(set_exclude(exclude_field, exclude_analyzer)) end end # all + exclude option if all query = { match_all: {} } should = [] else # higher score for matching more fields payload = { bool: { should: queries.map { |qs| {dis_max: {queries: qs}} } } } should.concat(set_conversions) should.concat(set_conversions_v2) end query = payload end payload = {} # type when inheritance where = ensure_permitted(options[:where] || {}).dup if searchkick_options[:inheritance] && (options[:type] || (klass != searchkick_klass && searchkick_index)) where[:type] = [options[:type] || klass].flatten.map { |v| searchkick_index.klass_document_type(v, true) } end models = Array(options[:models]) if models.any? { |m| m != m.searchkick_klass } index_type_or = models.map do |m| v = {_index: m.searchkick_index.name} v[:type] = m.searchkick_index.klass_document_type(m, true) if m != m.searchkick_klass v end where[:or] = Array(where[:or]) + [index_type_or] end # start everything as efficient filters # move to post_filters as aggs demand filters = where_filters(where) post_filters = [] # aggregations set_aggregations(payload, filters, post_filters) if options[:aggs] # post filters set_post_filters(payload, post_filters) if post_filters.any? custom_filters = [] multiply_filters = [] set_boost_by(multiply_filters, custom_filters) set_boost_where(custom_filters) set_boost_by_distance(custom_filters) if options[:boost_by_distance] set_boost_by_recency(custom_filters) if options[:boost_by_recency] payload[:query] = build_query(query, filters, should, must_not, custom_filters, multiply_filters) payload[:explain] = options[:explain] if options[:explain] payload[:profile] = options[:profile] if options[:profile] # order set_order(payload) if options[:order] # indices_boost set_boost_by_indices(payload) # suggestions set_suggestions(payload, options[:suggest]) if options[:suggest] # highlight set_highlights(payload, fields) if options[:highlight] # timeout shortly after client times out payload[:timeout] ||= "#{((Searchkick.search_timeout + 1) * 1000).round}ms" # An empty array will cause only the _id and _type for each hit to be returned # https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-source-filtering.html if options[:select] if options[:select] == [] # intuitively [] makes sense to return no fields, but ES by default returns all fields payload[:_source] = false else payload[:_source] = options[:select] end elsif load payload[:_source] = false end end # knn set_knn(payload, options[:knn], per_page, offset) if options[:knn] # pagination pagination_options = options[:page] || options[:limit] || options[:per_page] || options[:offset] || options[:padding] if !options[:body] || pagination_options payload[:size] = per_page payload[:from] = offset if offset > 0 end # type if !searchkick_options[:inheritance] && (options[:type] || (klass != searchkick_klass && searchkick_index)) @type = [options[:type] || klass].flatten.map { |v| searchkick_index.klass_document_type(v) } end # routing @routing = options[:routing] if options[:routing] if track_total_hits? payload[:track_total_hits] = true end # merge more body options payload = payload.deep_merge(options[:body_options]) if options[:body_options] # run block options[:block].call(payload) if options[:block] # scroll optimization when iterating over all docs # https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-scroll.html if options[:scroll] && payload[:query] == {match_all: {}} payload[:sort] ||= ["_doc"] end @body = payload @page = page @per_page = original_per_page @padding = padding @load = load @scroll = scroll @opaque_id = opaque_id end def set_fields boost_fields = {} fields = options[:fields] || searchkick_options[:default_fields] || searchkick_options[:searchable] all = searchkick_options.key?(:_all) ? searchkick_options[:_all] : false default_match = options[:match] || searchkick_options[:match] || :word fields = if fields fields.map do |value| k, v = value.is_a?(Hash) ? value.to_a.first : [value, default_match] k2, boost = k.to_s.split("^", 2) field = "#{k2}.#{v == :word ? 'analyzed' : v}" boost_fields[field] = boost.to_f if boost field end elsif all && default_match == :word ["_all"] elsif all && default_match == :phrase ["_all.phrase"] elsif term != "*" && default_match == :exact raise ArgumentError, "Must specify fields to search" else [default_match == :word ? "*.analyzed" : "*.#{default_match}"] end [boost_fields, fields] end def build_query(query, filters, should, must_not, custom_filters, multiply_filters) if filters.any? || must_not.any? || should.any? bool = {} bool[:must] = query if query bool[:filter] = filters if filters.any? # where bool[:must_not] = must_not if must_not.any? # exclude bool[:should] = should if should.any? # conversions query = {bool: bool} end if custom_filters.any? query = { function_score: { functions: custom_filters, query: query, score_mode: "sum" } } end if multiply_filters.any? query = { function_score: { functions: multiply_filters, query: query, score_mode: "multiply" } } end query end def set_conversions conversions_fields = Array(options[:conversions] || searchkick_options[:conversions]).map(&:to_s) if conversions_fields.present? && options[:conversions] != false conversions_fields.map do |conversions_field| { nested: { path: conversions_field, score_mode: "sum", query: { function_score: { boost_mode: "replace", query: { match: { "#{conversions_field}.query" => options[:conversions_term] || term } }, field_value_factor: { field: "#{conversions_field}.count" } } } } } end else [] end end def set_conversions_v2 conversions_v2 = options[:conversions_v2] return [] if conversions_v2.nil? && !searchkick_options[:conversions_v2] return [] if conversions_v2 == false # disable if searchkick_options[:conversions] to make it easy to upgrade without downtime return [] if conversions_v2.nil? && searchkick_options[:conversions] unless conversions_v2.is_a?(Hash) conversions_v2 = {field: conversions_v2} end conversions_fields = case conversions_v2[:field] when true, nil Array(searchkick_options[:conversions_v2]).map(&:to_s) else [conversions_v2[:field].to_s] end conversions_term = (conversions_v2[:term] || options[:conversions_term] || term).to_s unless searchkick_options[:case_sensitive] conversions_term = conversions_term.downcase end conversions_term = conversions_term.gsub(".", "*") conversions_fields.map do |conversions_field| { rank_feature: { field: "#{conversions_field}.#{conversions_term}", linear: {}, boost: conversions_v2[:factor] || 1 } } end end def set_exclude(field, analyzer) Array(options[:exclude]).map do |phrase| { multi_match: { fields: [field], query: phrase, analyzer: analyzer, type: "phrase" } } end end def set_boost_by_distance(custom_filters) boost_by_distance = options[:boost_by_distance] || {} # legacy format if boost_by_distance[:field] boost_by_distance = {boost_by_distance[:field] => boost_by_distance.except(:field)} end boost_by_distance.each do |field, attributes| attributes = {function: :gauss, scale: "5mi"}.merge(attributes) unless attributes[:origin] raise ArgumentError, "boost_by_distance requires :origin" end function_params = attributes.except(:factor, :function) function_params[:origin] = location_value(function_params[:origin]) custom_filters << { weight: attributes[:factor] || 1, attributes[:function] => { field => function_params } } end end def set_boost_by_recency(custom_filters) options[:boost_by_recency].each do |field, attributes| attributes = {function: :gauss, origin: Time.now}.merge(attributes) custom_filters << { weight: attributes[:factor] || 1, attributes[:function] => { field => attributes.except(:factor, :function) } } end end def set_boost_by(multiply_filters, custom_filters) boost_by = options[:boost_by] || {} if boost_by.is_a?(Array) boost_by = boost_by.to_h { |f| [f, {factor: 1}] } elsif boost_by.is_a?(Hash) multiply_by, boost_by = boost_by.transform_values(&:dup).partition { |_, v| v.delete(:boost_mode) == "multiply" }.map(&:to_h) end boost_by[options[:boost]] = {factor: 1} if options[:boost] custom_filters.concat boost_filters(boost_by, modifier: "ln2p") multiply_filters.concat boost_filters(multiply_by || {}) end def set_boost_where(custom_filters) boost_where = options[:boost_where] || {} boost_where.each do |field, value| if value.is_a?(Array) && value.first.is_a?(Hash) value.each do |value_factor| custom_filters << custom_filter(field, value_factor[:value], value_factor[:factor]) end elsif value.is_a?(Hash) custom_filters << custom_filter(field, value[:value], value[:factor]) else factor = 1000 custom_filters << custom_filter(field, value, factor) end end end def set_boost_by_indices(payload) return unless options[:indices_boost] indices_boost = options[:indices_boost].map do |key, boost| index = key.respond_to?(:searchkick_index) ? key.searchkick_index.name : key {index => boost} end payload[:indices_boost] = indices_boost end def set_suggestions(payload, suggest) suggest_fields = nil if suggest.is_a?(Array) suggest_fields = suggest else suggest_fields = (searchkick_options[:suggest] || []).map(&:to_s) # intersection if options[:fields] suggest_fields &= options[:fields].map { |v| (v.is_a?(Hash) ? v.keys.first : v).to_s.split("^", 2).first } end end if suggest_fields.any? payload[:suggest] = {text: term} suggest_fields.each do |field| payload[:suggest][field] = { phrase: { field: "#{field}.suggest" } } end else raise ArgumentError, "Must pass fields to suggest option" end end def set_highlights(payload, fields) payload[:highlight] = { fields: fields.to_h { |f| [f, {}] }, fragment_size: 0 } if options[:highlight].is_a?(Hash) if (tag = options[:highlight][:tag]) payload[:highlight][:pre_tags] = [tag] payload[:highlight][:post_tags] = [tag.to_s.gsub(/\A<(\w+).+/, "</\\1>")] end if (fragment_size = options[:highlight][:fragment_size]) payload[:highlight][:fragment_size] = fragment_size end if (encoder = options[:highlight][:encoder]) payload[:highlight][:encoder] = encoder end highlight_fields = options[:highlight][:fields] if highlight_fields payload[:highlight][:fields] = {} highlight_fields.each do |name, opts| payload[:highlight][:fields]["#{name}.#{@match_suffix}"] = opts || {} end end end @highlighted_fields = payload[:highlight][:fields].keys end def set_aggregations(payload, filters, post_filters) aggs = options[:aggs] payload[:aggs] = {} aggs = aggs.to_h { |f| [f, {}] } if aggs.is_a?(Array) # convert to more advanced syntax aggs.each do |field, agg_options| size = agg_options[:limit] ? agg_options[:limit] : 1_000 shared_agg_options = agg_options.except(:limit, :field, :ranges, :date_ranges, :where) if agg_options[:ranges] payload[:aggs][field] = { range: { field: agg_options[:field] || field, ranges: agg_options[:ranges] }.merge(shared_agg_options) } elsif agg_options[:date_ranges] payload[:aggs][field] = { date_range: { field: agg_options[:field] || field, ranges: agg_options[:date_ranges] }.merge(shared_agg_options) } elsif (histogram = agg_options[:date_histogram]) payload[:aggs][field] = { date_histogram: histogram }.merge(shared_agg_options) elsif (metric = @@metric_aggs.find { |k| agg_options.has_key?(k) }) payload[:aggs][field] = { metric => { field: agg_options[metric][:field] || field } }.merge(shared_agg_options) else payload[:aggs][field] = { terms: { field: agg_options[:field] || field, size: size }.merge(shared_agg_options) } end where = {} where = ensure_permitted(options[:where] || {}).reject { |k| k == field } unless options[:smart_aggs] == false agg_where = ensure_permitted(agg_options[:where] || {}) agg_filters = where_filters(where.merge(agg_where)) # only do one level comparison for simplicity filters.select! do |filter| if agg_filters.include?(filter) true else post_filters << filter false end end if agg_filters.any? payload[:aggs][field] = { filter: { bool: { must: agg_filters } }, aggs: { field => payload[:aggs][field] } } end end end def set_knn(payload, knn, per_page, offset) if term != "*" raise ArgumentError, "Use Searchkick.multi_search for hybrid search" end field = knn[:field] field_options = searchkick_options.dig(:knn, field.to_sym) || searchkick_options.dig(:knn, field.to_s) || {} vector = knn[:vector] distance = knn[:distance] || field_options[:distance] exact = knn[:exact] exact = field_options[:distance].nil? || distance != field_options[:distance] if exact.nil? k = per_page + offset ef_search = knn[:ef_search] filter = payload.delete(:query) if distance.nil? raise ArgumentError, "distance required" elsif !exact && distance != field_options[:distance] raise ArgumentError, "distance must match searchkick options for approximate search" end if Searchkick.opensearch? if exact # https://opensearch.org/docs/latest/search-plugins/knn/knn-score-script/#spaces space_type = case distance when "cosine" "cosinesimil" when "euclidean" "l2" when "taxicab" "l1" when "inner_product" "innerproduct" when "chebyshev" "linf" else raise ArgumentError, "Unknown distance: #{distance}" end payload[:query] = { script_score: { query: { bool: { must: [filter, {exists: {field: field}}] } }, script: { source: "knn_score", lang: "knn", params: { field: field, query_value: vector, space_type: space_type } }, boost: distance == "cosine" && Searchkick.server_below?("2.19.0") ? 0.5 : 1.0 } } else if ef_search && Searchkick.server_below?("2.16.0") raise Error, "ef_search requires OpenSearch 2.16+" end payload[:query] = { knn: { field.to_sym => { vector: vector, k: k, filter: filter }.merge(ef_search ? {method_parameters: {ef_search: ef_search}} : {}) } } end else if exact # prevent incorrect distances/results with Elasticsearch 9.0.0-rc1
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
true
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/relation.rb
lib/searchkick/relation.rb
module Searchkick class Relation NO_DEFAULT_VALUE = Object.new # note: modifying body directly is not supported # and has no impact on query after being executed # TODO freeze body object? delegate :params, to: :query delegate_missing_to :private_execute attr_reader :model alias_method :klass, :model def initialize(model, term = "*", **options) @model = model @term = term @options = options # generate query to validate options query end # same as Active Record def inspect entries = results.first(11).map!(&:inspect) entries[10] = "..." if entries.size == 11 "#<#{self.class.name} [#{entries.join(', ')}]>" end def aggs(value = NO_DEFAULT_VALUE) if value == NO_DEFAULT_VALUE private_execute.aggs else clone.aggs!(value) end end def aggs!(value) check_loaded (@options[:aggs] ||= {}).merge!(value) self end def body(value = NO_DEFAULT_VALUE) if value == NO_DEFAULT_VALUE query.body else clone.body!(value) end end def body!(value) check_loaded @options[:body] = value self end def body_options(value) clone.body_options!(value) end def body_options!(value) check_loaded (@options[:body_options] ||= {}).merge!(value) self end def boost(value) clone.boost!(value) end def boost!(value) check_loaded @options[:boost] = value self end def boost_by(value) clone.boost_by!(value) end def boost_by!(value) check_loaded if value.is_a?(Array) value = value.to_h { |f| [f, {factor: 1}] } elsif !value.is_a?(Hash) value = {value => {factor: 1}} end (@options[:boost_by] ||= {}).merge!(value) self end def boost_by_distance(value) clone.boost_by_distance!(value) end def boost_by_distance!(value) check_loaded # legacy format value = {value[:field] => value.except(:field)} if value[:field] (@options[:boost_by_distance] ||= {}).merge!(value) self end def boost_by_recency(value) clone.boost_by_recency!(value) end def boost_by_recency!(value) check_loaded (@options[:boost_by_recency] ||= {}).merge!(value) self end def boost_where(value) clone.boost_where!(value) end def boost_where!(value) check_loaded # TODO merge duplicate fields (@options[:boost_where] ||= {}).merge!(value) self end def conversions(value) clone.conversions!(value) end def conversions!(value) check_loaded @options[:conversions] = value self end def conversions_v1(value) clone.conversions_v1!(value) end def conversions_v1!(value) check_loaded @options[:conversions_v1] = value self end def conversions_v2(value) clone.conversions_v2!(value) end def conversions_v2!(value) check_loaded @options[:conversions_v2] = value self end def conversions_term(value) clone.conversions_term!(value) end def conversions_term!(value) check_loaded @options[:conversions_term] = value self end def debug(value = true) clone.debug!(value) end def debug!(value = true) check_loaded @options[:debug] = value self end def emoji(value = true) clone.emoji!(value) end def emoji!(value = true) check_loaded @options[:emoji] = value self end def exclude(*values) clone.exclude!(*values) end def exclude!(*values) check_loaded (@options[:exclude] ||= []).concat(values.flatten) self end def explain(value = true) clone.explain!(value) end def explain!(value = true) check_loaded @options[:explain] = value self end def fields(*values) clone.fields!(*values) end def fields!(*values) check_loaded (@options[:fields] ||= []).concat(values.flatten) self end def highlight(value) clone.highlight!(value) end def highlight!(value) check_loaded @options[:highlight] = value self end def includes(*values) clone.includes!(*values) end def includes!(*values) check_loaded (@options[:includes] ||= []).concat(values.flatten) self end def index_name(*values) clone.index_name!(*values) end def index_name!(*values) check_loaded values = values.flatten if values.all? { |v| v.respond_to?(:searchkick_index) } models!(*values) else (@options[:index_name] ||= []).concat(values) self end end def indices_boost(value) clone.indices_boost!(value) end def indices_boost!(value) check_loaded (@options[:indices_boost] ||= {}).merge!(value) self end def knn(value) clone.knn!(value) end def knn!(value) check_loaded @options[:knn] = value self end def limit(value) clone.limit!(value) end def limit!(value) check_loaded @options[:limit] = value self end def load(value = NO_DEFAULT_VALUE) if value == NO_DEFAULT_VALUE private_execute self else clone.load!(value) end end def load!(value) check_loaded @options[:load] = value self end def match(value) clone.match!(value) end def match!(value) check_loaded @options[:match] = value self end def misspellings(value) clone.misspellings!(value) end def misspellings!(value) check_loaded @options[:misspellings] = value self end def models(*values) clone.models!(*values) end def models!(*values) check_loaded (@options[:models] ||= []).concat(values.flatten) self end def model_includes(*values) clone.model_includes!(*values) end def model_includes!(*values) check_loaded (@options[:model_includes] ||= []).concat(values.flatten) self end def offset(value = NO_DEFAULT_VALUE) if value == NO_DEFAULT_VALUE private_execute.offset else clone.offset!(value) end end def offset!(value) check_loaded @options[:offset] = value self end def opaque_id(value) clone.opaque_id!(value) end def opaque_id!(value) check_loaded @options[:opaque_id] = value self end def operator(value) clone.operator!(value) end def operator!(value) check_loaded @options[:operator] = value self end def order(*values) clone.order!(*values) end def order!(*values) check_loaded (@options[:order] ||= []).concat(values.flatten) self end def padding(value = NO_DEFAULT_VALUE) if value == NO_DEFAULT_VALUE private_execute.padding else clone.padding!(value) end end def padding!(value) check_loaded @options[:padding] = value self end def page(value) clone.page!(value) end def page!(value) check_loaded @options[:page] = value self end def per_page(value = NO_DEFAULT_VALUE) if value == NO_DEFAULT_VALUE private_execute.per_page else clone.per_page!(value) end end def per_page!(value) check_loaded # TODO set limit? @options[:per_page] = value self end def profile(value = true) clone.profile!(value) end def profile!(value = true) check_loaded @options[:profile] = value self end def request_params(value) clone.request_params!(value) end def request_params!(value) check_loaded (@options[:request_params] ||= {}).merge!(value) self end def routing(value) clone.routing!(value) end def routing!(value) check_loaded @options[:routing] = value self end def scope_results(value) clone.scope_results!(value) end def scope_results!(value) check_loaded @options[:scope_results] = value self end def scroll(value = NO_DEFAULT_VALUE, &block) if value == NO_DEFAULT_VALUE private_execute.scroll(&block) elsif block_given? clone.scroll!(value).scroll(&block) else clone.scroll!(value) end end def scroll!(value) check_loaded @options[:scroll] = value self end def select(*values, &block) if block_given? private_execute.select(*values, &block) else clone.select!(*values) end end def select!(*values) check_loaded (@options[:select] ||= []).concat(values.flatten) self end def similar(value = true) clone.similar!(value) end def similar!(value = true) check_loaded @options[:similar] = value self end def smart_aggs(value) clone.smart_aggs!(value) end def smart_aggs!(value) check_loaded @options[:smart_aggs] = value self end def suggest(value = true) clone.suggest!(value) end def suggest!(value = true) check_loaded @options[:suggest] = value self end def total_entries(value = NO_DEFAULT_VALUE) if value == NO_DEFAULT_VALUE private_execute.total_entries else clone.total_entries!(value) end end def total_entries!(value) check_loaded @options[:total_entries] = value self end def track(value = true) clone.track!(value) end def track!(value = true) check_loaded @options[:track] = value self end def type(*values) clone.type!(*values) end def type!(*values) check_loaded (@options[:type] ||= []).concat(values.flatten) self end def where(value = NO_DEFAULT_VALUE) if value == NO_DEFAULT_VALUE Where.new(self) else clone.where!(value) end end def where!(value) check_loaded if @options[:where] @options[:where] = {_and: [@options[:where], ensure_permitted(value)]} else @options[:where] = ensure_permitted(value) end self end def first(value = NO_DEFAULT_VALUE) result = if loaded? private_execute else limit = value == NO_DEFAULT_VALUE ? 1 : value previous_limit = (@options[:limit] || @options[:per_page])&.to_i if previous_limit && previous_limit < limit limit = previous_limit end limit(limit).load end if value == NO_DEFAULT_VALUE result.first else result.first(value) end end def pluck(*keys) if !loaded? && @options[:load] == false select(*keys).send(:private_execute).pluck(*keys) else private_execute.pluck(*keys) end end def reorder(*values) clone.reorder!(*values) end def reorder!(*values) check_loaded @options[:order] = values self end def reselect(*values) clone.reselect!(*values) end def reselect!(*values) check_loaded @options[:select] = values self end def rewhere(value) clone.rewhere!(value) end def rewhere!(value) check_loaded @options[:where] = ensure_permitted(value) self end def only(*keys) Relation.new(@model, @term, **@options.slice(*keys)) end def except(*keys) Relation.new(@model, @term, **@options.except(*keys)) end def loaded? !@execute.nil? end undef_method :respond_to_missing? def respond_to_missing?(...) Results.new(nil, nil, nil).respond_to?(...) || super end def to_json(...) private_execute.to_a.to_json(...) end def as_json(...) private_execute.to_a.as_json(...) end def to_yaml private_execute.to_a.to_yaml end private def private_execute @execute ||= query.execute end def query @query ||= Query.new(@model, @term, **@options) end def check_loaded raise Error, "Relation loaded" if loaded? # reset query since options will change @query = nil end # provides *very* basic protection from unfiltered parameters # this is not meant to be comprehensive and may be expanded in the future def ensure_permitted(obj) obj.to_h end def initialize_copy(other) super @execute = nil end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/where.rb
lib/searchkick/where.rb
module Searchkick class Where def initialize(relation) @relation = relation end def not(value) @relation.where(_not: value) end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/index_options.rb
lib/searchkick/index_options.rb
module Searchkick class IndexOptions attr_reader :options def initialize(index) @options = index.options end def index_options # mortal symbols are garbage collected in Ruby 2.2+ custom_settings = (options[:settings] || {}).deep_symbolize_keys custom_mappings = (options[:mappings] || {}).deep_symbolize_keys if options[:mappings] && !options[:merge_mappings] settings = custom_settings mappings = custom_mappings else settings = generate_settings.deep_symbolize_keys.deep_merge(custom_settings) mappings = generate_mappings.deep_symbolize_keys.deep_merge(custom_mappings) end set_deep_paging(settings) if options[:deep_paging] || options[:max_result_window] { settings: settings, mappings: mappings } end def generate_settings language = options[:language] language = language.call if language.respond_to?(:call) settings = { analysis: { analyzer: { searchkick_keyword: { type: "custom", tokenizer: "keyword", filter: ["lowercase"] + (options[:stem_conversions] ? ["searchkick_stemmer"] : []) }, default_analyzer => { type: "custom", # character filters -> tokenizer -> token filters # https://www.elastic.co/guide/en/elasticsearch/guide/current/analysis-intro.html char_filter: ["ampersand"], tokenizer: "standard", # synonym should come last, after stemming and shingle # shingle must come before searchkick_stemmer filter: ["lowercase", "asciifolding", "searchkick_index_shingle", "searchkick_stemmer"] }, searchkick_search: { type: "custom", char_filter: ["ampersand"], tokenizer: "standard", filter: ["lowercase", "asciifolding", "searchkick_search_shingle", "searchkick_stemmer"] }, searchkick_search2: { type: "custom", char_filter: ["ampersand"], tokenizer: "standard", filter: ["lowercase", "asciifolding", "searchkick_stemmer"] }, # https://github.com/leschenko/elasticsearch_autocomplete/blob/master/lib/elasticsearch_autocomplete/analyzers.rb searchkick_autocomplete_search: { type: "custom", tokenizer: "keyword", filter: ["lowercase", "asciifolding"] }, searchkick_word_search: { type: "custom", tokenizer: "standard", filter: ["lowercase", "asciifolding"] }, searchkick_suggest_index: { type: "custom", tokenizer: "standard", filter: ["lowercase", "asciifolding", "searchkick_suggest_shingle"] }, searchkick_text_start_index: { type: "custom", tokenizer: "keyword", filter: ["lowercase", "asciifolding", "searchkick_edge_ngram"] }, searchkick_text_middle_index: { type: "custom", tokenizer: "keyword", filter: ["lowercase", "asciifolding", "searchkick_ngram"] }, searchkick_text_end_index: { type: "custom", tokenizer: "keyword", filter: ["lowercase", "asciifolding", "reverse", "searchkick_edge_ngram", "reverse"] }, searchkick_word_start_index: { type: "custom", tokenizer: "standard", filter: ["lowercase", "asciifolding", "searchkick_edge_ngram"] }, searchkick_word_middle_index: { type: "custom", tokenizer: "standard", filter: ["lowercase", "asciifolding", "searchkick_ngram"] }, searchkick_word_end_index: { type: "custom", tokenizer: "standard", filter: ["lowercase", "asciifolding", "reverse", "searchkick_edge_ngram", "reverse"] } }, filter: { searchkick_index_shingle: { type: "shingle", token_separator: "" }, # lucky find https://web.archiveorange.com/archive/v/AAfXfQ17f57FcRINsof7 searchkick_search_shingle: { type: "shingle", token_separator: "", output_unigrams: false, output_unigrams_if_no_shingles: true }, searchkick_suggest_shingle: { type: "shingle", max_shingle_size: 5 }, searchkick_edge_ngram: { type: "edge_ngram", min_gram: 1, max_gram: 50 }, searchkick_ngram: { type: "ngram", min_gram: 1, max_gram: 50 }, searchkick_stemmer: { # use stemmer if language is lowercase, snowball otherwise type: language == language.to_s.downcase ? "stemmer" : "snowball", language: language || "English" } }, char_filter: { # https://www.elastic.co/guide/en/elasticsearch/guide/current/custom-analyzers.html # &_to_and ampersand: { type: "mapping", mappings: ["&=> and "] } } } } raise ArgumentError, "Can't pass both language and stemmer" if options[:stemmer] && language update_language(settings, language) update_stemming(settings) if Searchkick.env == "test" settings[:number_of_shards] = 1 settings[:number_of_replicas] = 0 end if options[:similarity] settings[:similarity] = {default: {type: options[:similarity]}} end settings[:index] = { max_ngram_diff: 49, max_shingle_diff: 4 } if options[:knn] unless Searchkick.knn_support? if Searchkick.opensearch? raise Error, "knn requires OpenSearch 2.4+" else raise Error, "knn requires Elasticsearch 8.6+" end end if Searchkick.opensearch? && options[:knn].any? { |_, v| !v[:distance].nil? } # only enable if doing approximate search settings[:index][:knn] = true end end add_synonyms(settings) add_search_synonyms(settings) if options[:special_characters] == false settings[:analysis][:analyzer].each_value do |analyzer_settings| analyzer_settings[:filter].reject! { |f| f == "asciifolding" } end end if options[:case_sensitive] settings[:analysis][:analyzer].each do |_, analyzer| analyzer[:filter].delete("lowercase") end end settings end def update_language(settings, language) case language when "chinese" settings[:analysis][:analyzer].merge!( default_analyzer => { type: "ik_smart" }, searchkick_search: { type: "ik_smart" }, searchkick_search2: { type: "ik_max_word" } ) when "chinese2", "smartcn" settings[:analysis][:analyzer].merge!( default_analyzer => { type: "smartcn" }, searchkick_search: { type: "smartcn" }, searchkick_search2: { type: "smartcn" } ) when "japanese", "japanese2" analyzer = { type: "custom", tokenizer: "kuromoji_tokenizer", filter: [ "kuromoji_baseform", "kuromoji_part_of_speech", "cjk_width", "ja_stop", "searchkick_stemmer", "lowercase" ] } settings[:analysis][:analyzer].merge!( default_analyzer => analyzer.deep_dup, searchkick_search: analyzer.deep_dup, searchkick_search2: analyzer.deep_dup ) settings[:analysis][:filter][:searchkick_stemmer] = { type: "kuromoji_stemmer" } when "korean" settings[:analysis][:analyzer].merge!( default_analyzer => { type: "openkoreantext-analyzer" }, searchkick_search: { type: "openkoreantext-analyzer" }, searchkick_search2: { type: "openkoreantext-analyzer" } ) when "korean2" settings[:analysis][:analyzer].merge!( default_analyzer => { type: "nori" }, searchkick_search: { type: "nori" }, searchkick_search2: { type: "nori" } ) when "vietnamese" settings[:analysis][:analyzer].merge!( default_analyzer => { type: "vi_analyzer" }, searchkick_search: { type: "vi_analyzer" }, searchkick_search2: { type: "vi_analyzer" } ) when "polish", "ukrainian" settings[:analysis][:analyzer].merge!( default_analyzer => { type: language }, searchkick_search: { type: language }, searchkick_search2: { type: language } ) end end def update_stemming(settings) if options[:stemmer] stemmer = options[:stemmer] # could also support snowball and stemmer case stemmer[:type] when "hunspell" # supports all token filter options settings[:analysis][:filter][:searchkick_stemmer] = stemmer else raise ArgumentError, "Unknown stemmer: #{stemmer[:type]}" end end stem = options[:stem] # language analyzer used stem = false if settings[:analysis][:analyzer][default_analyzer][:type] != "custom" if stem == false settings[:analysis][:filter].delete(:searchkick_stemmer) settings[:analysis][:analyzer].each do |_, analyzer| analyzer[:filter].delete("searchkick_stemmer") if analyzer[:filter] end end if options[:stemmer_override] stemmer_override = { type: "stemmer_override" } if options[:stemmer_override].is_a?(String) stemmer_override[:rules_path] = options[:stemmer_override] else stemmer_override[:rules] = options[:stemmer_override] end settings[:analysis][:filter][:searchkick_stemmer_override] = stemmer_override settings[:analysis][:analyzer].each do |_, analyzer| stemmer_index = analyzer[:filter].index("searchkick_stemmer") if analyzer[:filter] analyzer[:filter].insert(stemmer_index, "searchkick_stemmer_override") if stemmer_index end end if options[:stem_exclusion] settings[:analysis][:filter][:searchkick_stem_exclusion] = { type: "keyword_marker", keywords: options[:stem_exclusion] } settings[:analysis][:analyzer].each do |_, analyzer| stemmer_index = analyzer[:filter].index("searchkick_stemmer") if analyzer[:filter] analyzer[:filter].insert(stemmer_index, "searchkick_stem_exclusion") if stemmer_index end end end def generate_mappings mapping = {} keyword_mapping = {type: "keyword"} keyword_mapping[:ignore_above] = options[:ignore_above] || 30000 # conversions Array(options[:conversions]).each do |conversions_field| mapping[conversions_field] = { type: "nested", properties: { query: {type: default_type, analyzer: "searchkick_keyword"}, count: {type: "integer"} } } end Array(options[:conversions_v2]).each do |conversions_field| mapping[conversions_field] = { type: "rank_features" } end if (Array(options[:conversions_v2]).map(&:to_s) & Array(options[:conversions]).map(&:to_s)).any? raise ArgumentError, "Must have separate conversions fields" end mapping_options = [:suggest, :word, :text_start, :text_middle, :text_end, :word_start, :word_middle, :word_end, :highlight, :searchable, :filterable] .to_h { |type| [type, (options[type] || []).map(&:to_s)] } word = options[:word] != false && (!options[:match] || options[:match] == :word) mapping_options[:searchable].delete("_all") analyzed_field_options = {type: default_type, index: true, analyzer: default_analyzer.to_s} mapping_options.values.flatten.uniq.each do |field| fields = {} if options.key?(:filterable) && !mapping_options[:filterable].include?(field) fields[field] = {type: default_type, index: false} else fields[field] = keyword_mapping end if !options[:searchable] || mapping_options[:searchable].include?(field) if word fields[:analyzed] = analyzed_field_options if mapping_options[:highlight].include?(field) fields[:analyzed][:term_vector] = "with_positions_offsets" end end mapping_options.except(:highlight, :searchable, :filterable, :word).each do |type, f| if options[:match] == type || f.include?(field) fields[type] = {type: default_type, index: true, analyzer: "searchkick_#{type}_index"} end end end mapping[field] = fields[field].merge(fields: fields.except(field)) end (options[:locations] || []).map(&:to_s).each do |field| mapping[field] = { type: "geo_point" } end options[:geo_shape] = options[:geo_shape].product([{}]).to_h if options[:geo_shape].is_a?(Array) (options[:geo_shape] || {}).each do |field, shape_options| mapping[field] = shape_options.merge(type: "geo_shape") end (options[:knn] || []).each do |field, knn_options| distance = knn_options[:distance] quantization = knn_options[:quantization] if Searchkick.opensearch? if distance.nil? # avoid server crash if method not specified raise ArgumentError, "Must specify a distance for OpenSearch" end vector_options = { type: "knn_vector", dimension: knn_options[:dimensions] } if !distance.nil? space_type = case distance when "cosine" "cosinesimil" when "euclidean" "l2" when "inner_product" "innerproduct" else raise ArgumentError, "Unknown distance: #{distance}" end if !quantization.nil? raise ArgumentError, "Quantization not supported yet for OpenSearch" end vector_options[:method] = { name: "hnsw", space_type: space_type, engine: "lucene", parameters: knn_options.slice(:m, :ef_construction) } end mapping[field.to_s] = vector_options else vector_options = { type: "dense_vector", dims: knn_options[:dimensions], index: !distance.nil? } if !distance.nil? vector_options[:similarity] = case distance when "cosine" "cosine" when "euclidean" "l2_norm" when "inner_product" "max_inner_product" else raise ArgumentError, "Unknown distance: #{distance}" end type = case quantization when "int8", "int4", "bbq" "#{quantization}_hnsw" when nil "hnsw" else raise ArgumentError, "Unknown quantization: #{quantization}" end vector_index_options = knn_options.slice(:m, :ef_construction) vector_options[:index_options] = {type: type}.merge(vector_index_options) end mapping[field.to_s] = vector_options end end if options[:inheritance] mapping[:type] = keyword_mapping end routing = {} if options[:routing] routing = {required: true} unless options[:routing] == true routing[:path] = options[:routing].to_s end end dynamic_fields = { # analyzed field must be the default field for include_in_all # https://www.elastic.co/guide/reference/mapping/multi-field-type/ # however, we can include the not_analyzed field in _all # and the _all index analyzer will take care of it "{name}" => keyword_mapping } if options.key?(:filterable) dynamic_fields["{name}"] = {type: default_type, index: false} end unless options[:searchable] if options[:match] && options[:match] != :word dynamic_fields[options[:match]] = {type: default_type, index: true, analyzer: "searchkick_#{options[:match]}_index"} end if word dynamic_fields[:analyzed] = analyzed_field_options end end # https://www.elastic.co/guide/reference/mapping/multi-field-type/ multi_field = dynamic_fields["{name}"].merge(fields: dynamic_fields.except("{name}")) mappings = { properties: mapping, _routing: routing, # https://gist.github.com/kimchy/2898285 dynamic_templates: [ { string_template: { match: "*", match_mapping_type: "string", mapping: multi_field } } ] } mappings end def add_synonyms(settings) synonyms = options[:synonyms] || [] synonyms = synonyms.call if synonyms.respond_to?(:call) if synonyms.any? settings[:analysis][:filter][:searchkick_synonym] = { type: "synonym", # only remove a single space from synonyms so three-word synonyms will fail noisily instead of silently synonyms: synonyms.select { |s| s.size > 1 }.map { |s| s.is_a?(Array) ? s.map { |s2| s2.sub(/\s+/, "") }.join(",") : s }.map(&:downcase) } # choosing a place for the synonym filter when stemming is not easy # https://groups.google.com/forum/#!topic/elasticsearch/p7qcQlgHdB8 # TODO use a snowball stemmer on synonyms when creating the token filter # https://discuss.elastic.co/t/synonym-multi-words-search/10964 # I find the following approach effective if you are doing multi-word synonyms (synonym phrases): # - Only apply the synonym expansion at index time # - Don't have the synonym filter applied search # - Use directional synonyms where appropriate. You want to make sure that you're not injecting terms that are too general. settings[:analysis][:analyzer][default_analyzer][:filter].insert(2, "searchkick_synonym") %w(word_start word_middle word_end).each do |type| settings[:analysis][:analyzer]["searchkick_#{type}_index".to_sym][:filter].insert(2, "searchkick_synonym") end end end def add_search_synonyms(settings) search_synonyms = options[:search_synonyms] || [] search_synonyms = search_synonyms.call if search_synonyms.respond_to?(:call) if search_synonyms.is_a?(String) || search_synonyms.any? if search_synonyms.is_a?(String) synonym_graph = { type: "synonym_graph", synonyms_path: search_synonyms, updateable: true } else synonym_graph = { type: "synonym_graph", # TODO confirm this is correct synonyms: search_synonyms.select { |s| s.size > 1 }.map { |s| s.is_a?(Array) ? s.join(",") : s }.map(&:downcase) } end settings[:analysis][:filter][:searchkick_synonym_graph] = synonym_graph if ["japanese", "japanese2"].include?(options[:language]) [:searchkick_search, :searchkick_search2].each do |analyzer| settings[:analysis][:analyzer][analyzer][:filter].insert(4, "searchkick_synonym_graph") end else [:searchkick_search2, :searchkick_word_search].each do |analyzer| unless settings[:analysis][:analyzer][analyzer].key?(:filter) raise Error, "Search synonyms are not supported yet for language" end settings[:analysis][:analyzer][analyzer][:filter].insert(2, "searchkick_synonym_graph") end end end end def set_deep_paging(settings) if !settings.dig(:index, :max_result_window) && !settings[:"index.max_result_window"] settings[:index] ||= {} settings[:index][:max_result_window] = options[:max_result_window] || 1_000_000_000 end end def index_type @index_type ||= begin index_type = options[:_type] index_type = index_type.call if index_type.respond_to?(:call) index_type end end def default_type "text" end def default_analyzer :searchkick_index end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/railtie.rb
lib/searchkick/railtie.rb
module Searchkick class Railtie < Rails::Railtie rake_tasks do load "tasks/searchkick.rake" end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/reindex_v2_job.rb
lib/searchkick/reindex_v2_job.rb
module Searchkick class ReindexV2Job < Searchkick.parent_job.constantize queue_as { Searchkick.queue_name } def perform(class_name, id, method_name = nil, routing: nil, index_name: nil, ignore_missing: nil) model = Searchkick.load_model(class_name, allow_child: true) index = model.searchkick_index(name: index_name) # use should_index? to decide whether to index (not default scope) # just like saving inline # could use Searchkick.scope() in future # but keep for now for backwards compatibility model = model.unscoped if model.respond_to?(:unscoped) items = [{id: id, routing: routing}] RecordIndexer.new(index).reindex_items(model, items, method_name: method_name, ignore_missing: ignore_missing, single: true) end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/results.rb
lib/searchkick/results.rb
module Searchkick class Results include Enumerable extend Forwardable attr_reader :response def_delegators :results, :each, :any?, :empty?, :size, :length, :slice, :[], :to_ary def initialize(klass, response, options = {}) @klass = klass @response = response @options = options end def with_hit return enum_for(:with_hit) unless block_given? build_hits.each do |result| yield result end end def missing_records @missing_records ||= with_hit_and_missing_records[1] end def suggestions if response["suggest"] response["suggest"].values.flat_map { |v| v.first["options"] }.sort_by { |o| -o["score"] }.map { |o| o["text"] }.uniq elsif options[:suggest] [] else raise "Pass `suggest: true` to the search method for suggestions" end end def aggregations response["aggregations"] end def aggs @aggs ||= begin if aggregations aggregations.dup.each do |field, filtered_agg| buckets = filtered_agg[field] # move the buckets one level above into the field hash if buckets filtered_agg.delete(field) filtered_agg.merge!(buckets) end end end end end def took response["took"] end def error response["error"] end def model_name if klass.nil? ActiveModel::Name.new(self.class, nil, 'Result') else klass.model_name end end def entry_name(options = {}) if options.empty? # backward compatibility model_name.human.downcase else default = options[:count] == 1 ? model_name.human : model_name.human.pluralize model_name.human(options.reverse_merge(default: default)) end end def total_count if options[:total_entries] options[:total_entries] elsif response["hits"]["total"].is_a?(Hash) response["hits"]["total"]["value"] else response["hits"]["total"] end end alias_method :total_entries, :total_count def current_page options[:page] end def per_page options[:per_page] end alias_method :limit_value, :per_page def padding options[:padding] end def total_pages (total_count / per_page.to_f).ceil end alias_method :num_pages, :total_pages def offset_value (current_page - 1) * per_page + padding end alias_method :offset, :offset_value def previous_page current_page > 1 ? (current_page - 1) : nil end alias_method :prev_page, :previous_page def next_page current_page < total_pages ? (current_page + 1) : nil end def first_page? previous_page.nil? end def last_page? next_page.nil? end def out_of_range? current_page > total_pages end def hits if error raise Error, "Query error - use the error method to view it" else @response["hits"]["hits"] end end def highlights(multiple: false) hits.map do |hit| hit_highlights(hit, multiple: multiple) end end def with_highlights(multiple: false) return enum_for(:with_highlights, multiple: multiple) unless block_given? with_hit.each do |result, hit| yield result, hit_highlights(hit, multiple: multiple) end end def with_score return enum_for(:with_score) unless block_given? with_hit.each do |result, hit| yield result, hit["_score"] end end def misspellings? @options[:misspellings] end def scroll_id @response["_scroll_id"] end def scroll raise Error, "Pass `scroll` option to the search method for scrolling" unless scroll_id if block_given? records = self while records.any? yield records records = records.scroll end records.clear_scroll else begin # TODO Active Support notifications for this scroll call params = { scroll: options[:scroll], body: {scroll_id: scroll_id} } params[:opaque_id] = options[:opaque_id] if options[:opaque_id] Results.new(@klass, Searchkick.client.scroll(params), @options) rescue => e if Searchkick.not_found_error?(e) && e.message =~ /search_context_missing_exception/i raise Error, "Scroll id has expired" else raise e end end end end def clear_scroll begin # try to clear scroll # not required as scroll will expire # but there is a cost to open scrolls Searchkick.client.clear_scroll(scroll_id: scroll_id) rescue => e raise e unless Searchkick.transport_error?(e) end end private attr_reader :klass, :options def results @results ||= with_hit.map(&:first) end def with_hit_and_missing_records @with_hit_and_missing_records ||= begin missing_records = [] if options[:load] grouped_hits = hits.group_by { |hit, _| hit["_index"] } # determine models index_models = {} grouped_hits.each do |index, _| models = if @klass [@klass] else index_alias = index.split("_")[0..-2].join("_") Array((options[:index_mapping] || {})[index_alias]) end raise Error, "Unknown model for index: #{index}. Pass the `models` option to the search method." unless models.any? index_models[index] = models end # fetch results results = {} grouped_hits.each do |index, index_hits| results[index] = {} index_models[index].each do |model| results[index].merge!(results_query(model, index_hits).to_a.index_by { |r| r.id.to_s }) end end # sort results = hits.map do |hit| result = results[hit["_index"]][hit["_id"].to_s] if result && !(options[:load].is_a?(Hash) && options[:load][:dumpable]) if (hit["highlight"] || options[:highlight]) && !result.respond_to?(:search_highlights) highlights = hit_highlights(hit) result.define_singleton_method(:search_highlights) do highlights end end end [result, hit] end.select do |result, hit| unless result models = index_models[hit["_index"]] missing_records << { id: hit["_id"], # may be multiple models for inheritance with child models # not ideal to return different types # but this situation shouldn't be common model: models.size == 1 ? models.first : models } end result end else results = hits.map do |hit| result = if hit["_source"] hit.except("_source").merge(hit["_source"]) elsif hit["fields"] hit.except("fields").merge(hit["fields"]) else hit end if hit["highlight"] || options[:highlight] highlight = hit["highlight"].to_a.to_h { |k, v| [base_field(k), v.first] } options[:highlighted_fields].map { |k| base_field(k) }.each do |k| result["highlighted_#{k}"] ||= (highlight[k] || result[k]) end end result["id"] ||= result["_id"] # needed for legacy reasons [HashWrapper.new(result), hit] end end [results, missing_records] end end def build_hits @build_hits ||= begin if missing_records.any? Searchkick.warn("Records in search index do not exist in database: #{missing_records.map { |v| "#{Array(v[:model]).map(&:model_name).sort.join("/")} #{v[:id]}" }.join(", ")}") end with_hit_and_missing_records[0] end end def results_query(records, hits) records = Searchkick.scope(records) ids = hits.map { |hit| hit["_id"] } if options[:includes] || options[:model_includes] included_relations = [] combine_includes(included_relations, options[:includes]) combine_includes(included_relations, options[:model_includes][records]) if options[:model_includes] records = records.includes(included_relations) end if options[:scope_results] records = options[:scope_results].call(records) end Searchkick.load_records(records, ids) end def combine_includes(result, inc) if inc if inc.is_a?(Array) result.concat(inc) else result << inc end end end def base_field(k) k.sub(/\.(analyzed|word_start|word_middle|word_end|text_start|text_middle|text_end|exact)\z/, "") end def hit_highlights(hit, multiple: false) if hit["highlight"] hit["highlight"].to_h { |k, v| [(options[:json] ? k : k.sub(/\.#{@options[:match_suffix]}\z/, "")).to_sym, multiple ? v : v.first] } else {} end end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/bulk_reindex_job.rb
lib/searchkick/bulk_reindex_job.rb
module Searchkick class BulkReindexJob < Searchkick.parent_job.constantize queue_as { Searchkick.queue_name } def perform(class_name:, record_ids: nil, index_name: nil, method_name: nil, batch_id: nil, min_id: nil, max_id: nil, ignore_missing: nil) model = Searchkick.load_model(class_name) index = model.searchkick_index(name: index_name) record_ids ||= min_id..max_id relation = Searchkick.scope(model) relation = Searchkick.load_records(relation, record_ids) relation = relation.search_import if relation.respond_to?(:search_import) RecordIndexer.new(index).reindex(relation, mode: :inline, method_name: method_name, ignore_missing: ignore_missing, full: false) RelationIndexer.new(index).batch_completed(batch_id) if batch_id end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/indexer.rb
lib/searchkick/indexer.rb
# thread-local (technically fiber-local) indexer # used to aggregate bulk callbacks across models module Searchkick class Indexer attr_reader :queued_items def initialize @queued_items = [] end def queue(items) @queued_items.concat(items) perform unless Searchkick.callbacks_value == :bulk end def perform items = @queued_items @queued_items = [] return if items.empty? response = Searchkick.client.bulk(body: items) if response["errors"] # note: delete does not set error when item not found first_with_error = response["items"].map do |item| (item["index"] || item["delete"] || item["update"]) end.find.with_index { |item, i| item["error"] && !ignore_missing?(items[i], item["error"]) } if first_with_error raise ImportError, "#{first_with_error["error"]} on item with id '#{first_with_error["_id"]}'" end end # maybe return response in future nil end private def ignore_missing?(item, error) error["type"] == "document_missing_exception" && item.instance_variable_defined?(:@ignore_missing) end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/multi_search.rb
lib/searchkick/multi_search.rb
module Searchkick class MultiSearch attr_reader :queries def initialize(queries, opaque_id: nil) @queries = queries @opaque_id = opaque_id end def perform if queries.any? perform_search(queries) end end private def perform_search(search_queries, perform_retry: true) params = { body: search_queries.flat_map { |q| [q.params.except(:body), q.body] } } params[:opaque_id] = @opaque_id if @opaque_id responses = client.msearch(params)["responses"] retry_queries = [] search_queries.each_with_index do |query, i| if perform_retry && query.retry_misspellings?(responses[i]) query.send(:prepare) # okay, since we don't want to expose this method outside Searchkick retry_queries << query else query.handle_response(responses[i]) end end if retry_queries.any? perform_search(retry_queries, perform_retry: false) end search_queries end def client Searchkick.client end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/relation_indexer.rb
lib/searchkick/relation_indexer.rb
module Searchkick class RelationIndexer attr_reader :index def initialize(index) @index = index end def reindex(relation, mode:, method_name: nil, ignore_missing: nil, full: false, resume: false, scope: nil, job_options: nil) # apply scopes if scope relation = relation.send(scope) elsif relation.respond_to?(:search_import) relation = relation.search_import end # remove unneeded loading for async and queue if mode == :async || mode == :queue if relation.respond_to?(:primary_key) relation = relation.except(:includes, :preload) unless mode == :queue && relation.klass.method_defined?(:search_routing) relation = relation.except(:select).select(relation.primary_key) end elsif relation.respond_to?(:only) unless mode == :queue && relation.klass.method_defined?(:search_routing) relation = relation.only(:_id) end end end if mode == :async && full return full_reindex_async(relation, job_options: job_options) end relation = resume_relation(relation) if resume reindex_options = { mode: mode, method_name: method_name, full: full, ignore_missing: ignore_missing, job_options: job_options } record_indexer = RecordIndexer.new(index) in_batches(relation) do |items| record_indexer.reindex(items, **reindex_options) end end def batches_left Searchkick.with_redis { |r| r.call("SCARD", batches_key) } end def batch_completed(batch_id) Searchkick.with_redis { |r| r.call("SREM", batches_key, [batch_id]) } end private def resume_relation(relation) if relation.respond_to?(:primary_key) # use total docs instead of max id since there's not a great way # to get the max _id without scripting since it's a string where = relation.arel_table[relation.primary_key].gt(index.total_docs) relation = relation.where(where) else raise Error, "Resume not supported for Mongoid" end end def in_batches(relation) if relation.respond_to?(:find_in_batches) klass = relation.klass # remove order to prevent possible warnings relation.except(:order).find_in_batches(batch_size: batch_size) do |batch| # prevent scope from affecting search_data as well as inline jobs # Active Record runs relation calls in scoping block # https://github.com/rails/rails/blob/main/activerecord/lib/active_record/relation/delegation.rb # note: we could probably just call klass.current_scope = nil # anywhere in reindex method (after initial all call), # but this is more cautious previous_scope = klass.current_scope(true) if previous_scope begin klass.current_scope = nil yield batch ensure klass.current_scope = previous_scope end else yield batch end end else klass = relation.klass each_batch(relation, batch_size: batch_size) do |batch| # prevent scope from affecting search_data as well as inline jobs # note: Model.with_scope doesn't always restore scope, so use custom logic previous_scope = Mongoid::Threaded.current_scope(klass) if previous_scope begin Mongoid::Threaded.set_current_scope(nil, klass) yield batch ensure Mongoid::Threaded.set_current_scope(previous_scope, klass) end else yield batch end end end end def each_batch(relation, batch_size:) # https://github.com/karmi/tire/blob/master/lib/tire/model/import.rb # use cursor for Mongoid items = [] relation.all.each do |item| items << item if items.length == batch_size yield items items = [] end end yield items if items.any? end def batch_size @batch_size ||= index.options[:batch_size] || 1000 end def full_reindex_async(relation, job_options: nil) batch_id = 1 class_name = relation.searchkick_options[:class_name] starting_id = false if relation.respond_to?(:primary_key) primary_key = relation.primary_key starting_id = begin relation.minimum(primary_key) rescue ActiveRecord::StatementInvalid false end end if starting_id.nil? # no records, do nothing elsif starting_id.is_a?(Numeric) max_id = relation.maximum(primary_key) batches_count = ((max_id - starting_id + 1) / batch_size.to_f).ceil batches_count.times do |i| min_id = starting_id + (i * batch_size) batch_job(class_name, batch_id, job_options, min_id: min_id, max_id: min_id + batch_size - 1) batch_id += 1 end else in_batches(relation) do |items| batch_job(class_name, batch_id, job_options, record_ids: items.map(&:id).map { |v| v.instance_of?(Integer) ? v : v.to_s }) batch_id += 1 end end end def batch_job(class_name, batch_id, job_options, **options) job_options ||= {} # TODO expire Redis key Searchkick.with_redis { |r| r.call("SADD", batches_key, [batch_id]) } Searchkick::BulkReindexJob.set(**job_options).perform_later( class_name: class_name, index_name: index.name, batch_id: batch_id, **options ) end def batches_key "searchkick:reindex:#{index.name}:batches" end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/process_batch_job.rb
lib/searchkick/process_batch_job.rb
module Searchkick class ProcessBatchJob < Searchkick.parent_job.constantize queue_as { Searchkick.queue_name } def perform(class_name:, record_ids:, index_name: nil) model = Searchkick.load_model(class_name) index = model.searchkick_index(name: index_name) items = record_ids.map do |r| parts = r.split(/(?<!\|)\|(?!\|)/, 2) .map { |v| v.gsub("||", "|") } {id: parts[0], routing: parts[1]} end relation = Searchkick.scope(model) RecordIndexer.new(index).reindex_items(relation, items, method_name: nil, ignore_missing: nil) end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/model.rb
lib/searchkick/model.rb
module Searchkick module Model def searchkick(**options) options = Searchkick.model_options.deep_merge(options) if options[:conversions] Searchkick.warn("The `conversions` option is deprecated in favor of `conversions_v2`, which provides much better search performance. Upgrade to `conversions_v2` or rename `conversions` to `conversions_v1`") end if options.key?(:conversions_v1) options[:conversions] = options.delete(:conversions_v1) end unknown_keywords = options.keys - [:_all, :_type, :batch_size, :callbacks, :callback_options, :case_sensitive, :conversions, :conversions_v2, :deep_paging, :default_fields, :filterable, :geo_shape, :highlight, :ignore_above, :index_name, :index_prefix, :inheritance, :job_options, :knn, :language, :locations, :mappings, :match, :max_result_window, :merge_mappings, :routing, :searchable, :search_synonyms, :settings, :similarity, :special_characters, :stem, :stemmer, :stem_conversions, :stem_exclusion, :stemmer_override, :suggest, :synonyms, :text_end, :text_middle, :text_start, :unscope, :word, :word_end, :word_middle, :word_start] raise ArgumentError, "unknown keywords: #{unknown_keywords.join(", ")}" if unknown_keywords.any? raise "Only call searchkick once per model" if respond_to?(:searchkick_index) Searchkick.models << self options[:_type] ||= -> { searchkick_index.klass_document_type(self, true) } options[:class_name] = model_name.name callbacks = options.key?(:callbacks) ? options[:callbacks] : :inline unless [:inline, true, false, :async, :queue].include?(callbacks) raise ArgumentError, "Invalid value for callbacks" end callback_options = (options[:callback_options] || {}).dup callback_options[:if] = [-> { Searchkick.callbacks?(default: callbacks) }, callback_options[:if]].compact.flatten(1) base = self mod = Module.new include(mod) mod.module_eval do def reindex(method_name = nil, mode: nil, refresh: false, ignore_missing: nil, job_options: nil) self.class.searchkick_index.reindex([self], method_name: method_name, mode: mode, refresh: refresh, ignore_missing: ignore_missing, job_options: job_options, single: true) end unless base.method_defined?(:reindex) def similar(**options) self.class.searchkick_index.similar_record(self, **options) end unless base.method_defined?(:similar) def search_data data = respond_to?(:to_hash) ? to_hash : serializable_hash data.delete("id") data.delete("_id") data.delete("_type") data end unless base.method_defined?(:search_data) def should_index? true end unless base.method_defined?(:should_index?) end class_eval do cattr_reader :searchkick_options, :searchkick_klass, instance_reader: false class_variable_set :@@searchkick_options, options.dup class_variable_set :@@searchkick_klass, self class_variable_set :@@searchkick_index_cache, Searchkick::IndexCache.new class << self def searchkick_search(term = "*", **options, &block) if Searchkick.relation?(self) raise Searchkick::Error, "search must be called on model, not relation" end Searchkick.search(term, model: self, **options, &block) end alias_method Searchkick.search_method_name, :searchkick_search if Searchkick.search_method_name def searchkick_index(name: nil) index_name = name || searchkick_klass.searchkick_index_name index_name = index_name.call if index_name.respond_to?(:call) index_cache = class_variable_get(:@@searchkick_index_cache) index_cache.fetch(index_name) { Searchkick::Index.new(index_name, searchkick_options) } end alias_method :search_index, :searchkick_index unless method_defined?(:search_index) def searchkick_reindex(method_name = nil, **options) searchkick_index.reindex(self, method_name: method_name, **options) end alias_method :reindex, :searchkick_reindex unless method_defined?(:reindex) def searchkick_index_options searchkick_index.index_options end def searchkick_index_name @searchkick_index_name ||= begin options = class_variable_get(:@@searchkick_options) if options[:index_name] options[:index_name] elsif options[:index_prefix].respond_to?(:call) -> { [options[:index_prefix].call, model_name.plural, Searchkick.env, Searchkick.index_suffix].compact.join("_") } else [options.key?(:index_prefix) ? options[:index_prefix] : Searchkick.index_prefix, model_name.plural, Searchkick.env, Searchkick.index_suffix].compact.join("_") end end end end # always add callbacks, even when callbacks is false # so Model.callbacks block can be used if respond_to?(:after_commit) after_commit :reindex, **callback_options elsif respond_to?(:after_save) after_save :reindex, **callback_options after_destroy :reindex, **callback_options end end end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
ankane/searchkick
https://github.com/ankane/searchkick/blob/107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b/lib/searchkick/reranking.rb
lib/searchkick/reranking.rb
module Searchkick module Reranking def self.rrf(first_ranking, *rankings, k: 60) rankings.unshift(first_ranking) rankings.map!(&:to_ary) ranks = [] results = [] rankings.each do |ranking| ranks << ranking.map.with_index.to_h { |v, i| [v, i + 1] } results.concat(ranking) end results = results.uniq.map do |result| score = ranks.sum do |rank| r = rank[result] r ? 1.0 / (k + r) : 0.0 end {result: result, score: score} end results.sort_by { |v| -v[:score] } end end end
ruby
MIT
107d270a0d2d7e1935dc7fee1ea0305edb5e4b3b
2026-01-04T15:40:12.176737Z
false
busyloop/lolcat
https://github.com/busyloop/lolcat/blob/f4cca5601ea57df2b5b3c98feea8ad05f4421039/lib/lolcat.rb
lib/lolcat.rb
# Copyright (c) 2016, moe@busyloop.net # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the lolcat nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. require "lolcat/version" require "lolcat/lol" require "lolcat/cat"
ruby
BSD-3-Clause
f4cca5601ea57df2b5b3c98feea8ad05f4421039
2026-01-04T15:40:26.663979Z
false
busyloop/lolcat
https://github.com/busyloop/lolcat/blob/f4cca5601ea57df2b5b3c98feea8ad05f4421039/lib/lolcat/version.rb
lib/lolcat/version.rb
module Lolcat VERSION = "100.0.1" end
ruby
BSD-3-Clause
f4cca5601ea57df2b5b3c98feea8ad05f4421039
2026-01-04T15:40:26.663979Z
false
busyloop/lolcat
https://github.com/busyloop/lolcat/blob/f4cca5601ea57df2b5b3c98feea8ad05f4421039/lib/lolcat/lol.rb
lib/lolcat/lol.rb
# Copyright (c) 2016, moe@busyloop.net # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the lolcat nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. require "lolcat/version" require 'paint' module Lol ANSI_ESCAPE = /((?:\e(?:[ -\/]+.|[\]PX^_][^\a\e]*|\[[0-?]*.|.))*)(.?)/m INCOMPLETE_ESCAPE = /\e(?:[ -\/]*|[\]PX^_][^\a\e]*|\[[0-?]*)$/ @os = 0 @paint_init = false def self.rainbow(freq, i) red = Math.sin(freq*i + 0) * 127 + 128 green = Math.sin(freq*i + 2*Math::PI/3) * 127 + 128 blue = Math.sin(freq*i + 4*Math::PI/3) * 127 + 128 "#%02X%02X%02X" % [ red, green, blue ] end def self.cat(fd, opts={}) @os = opts[:os] print "\e[?25l" if opts[:animate] while true do buf = '' begin begin buf += fd.sysread(4096) invalid_encoding = !buf.dup.force_encoding(fd.external_encoding).valid_encoding? end while invalid_encoding or buf.match(INCOMPLETE_ESCAPE) rescue EOFError break end buf.force_encoding(fd.external_encoding) buf.lines.each do |line| @os += 1 println(line, opts) end end ensure if STDOUT.tty? then print "\e[m\e[?25h\e[?1;5;2004l" # system("stty sane -istrip <&1"); end end def self.println(str, defaults={}, opts={}) opts.merge!(defaults) chomped = str.sub!(/\n$/, "") str.gsub! "\t", " " opts[:animate] ? println_ani(str, opts, chomped) : println_plain(str, opts, chomped) puts if chomped end private def self.println_plain(str, defaults={}, opts={}, chomped) opts.merge!(defaults) set_mode(opts[:truecolor]) unless @paint_init filtered = str.scan(ANSI_ESCAPE) filtered.each_with_index do |c, i| color = rainbow(opts[:freq], @os+i/opts[:spread]) if opts[:invert] then print c[0], Paint.color(nil, color), c[1], "\e[49m" else print c[0], Paint.color(color), c[1], "\e[39m" end end if chomped == nil @old_os = @os @os = @os + filtered.length/opts[:spread] elsif @old_os @os = @old_os @old_os = nil end end def self.println_ani(str, opts={}, chomped) return if str.empty? print "\e7" @real_os = @os (1..opts[:duration]).each do |i| print "\e8" @os += opts[:spread] println_plain(str, opts, chomped) str.gsub!(/\e\[[0-?]*[@JKPX]/, "") sleep 1.0/opts[:speed] end @os = @real_os end def self.set_mode(truecolor) # @paint_mode_detected = Paint.mode @paint_mode_detected = %w[truecolor 24bit].include?(ENV['COLORTERM']) ? 0xffffff : 256 Paint.mode = truecolor ? 0xffffff : @paint_mode_detected STDERR.puts "DEBUG: Paint.mode = #{Paint.mode} (detected: #{@paint_mode_detected})" if ENV['LOLCAT_DEBUG'] @paint_init = true end end
ruby
BSD-3-Clause
f4cca5601ea57df2b5b3c98feea8ad05f4421039
2026-01-04T15:40:26.663979Z
false
busyloop/lolcat
https://github.com/busyloop/lolcat/blob/f4cca5601ea57df2b5b3c98feea8ad05f4421039/lib/lolcat/cat.rb
lib/lolcat/cat.rb
# Copyright (c) 2016, moe@busyloop.net # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the lolcat nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. require "lolcat/version" require "lolcat/lol" require 'stringio' require 'optimist' module Lol def self.cat! p = Optimist::Parser.new do version "lolcat #{Lolcat::VERSION} (c)2011 moe@busyloop.net" banner <<HEADER Usage: lolcat [OPTION]... [FILE]... Concatenate FILE(s), or standard input, to standard output. With no FILE, or when FILE is -, read standard input. HEADER banner '' opt :spread, "Rainbow spread", :short => 'p', :default => 3.0 opt :freq, "Rainbow frequency", :short => 'F', :default => 0.1 opt :seed, "Rainbow seed, 0 = random", :short => 'S', :default => 0 opt :animate, "Enable psychedelics", :short => 'a', :default => false opt :duration, "Animation duration", :short => 'd', :default => 12 opt :speed, "Animation speed", :short => 's', :default => 20.0 opt :invert, "Invert fg and bg", :short => 'i', :default => false opt :truecolor, "24-bit (truecolor)", :short => 't', :default => false opt :force, "Force color even when stdout is not a tty", :short => 'f', :default => false opt :version, "Print version and exit", :short => 'v' opt :help, "Show this message", :short => 'h' banner <<FOOTER Examples: lolcat f - g Output f's contents, then stdin, then g's contents. lolcat Copy standard input to standard output. fortune | lolcat Display a rainbow cookie. Report lolcat bugs to <https://github.com/busyloop/lolcat/issues> lolcat home page: <https://github.com/busyloop/lolcat/> Report lolcat translation bugs to <http://speaklolcat.com/> FOOTER end opts = Optimist::with_standard_exception_handling p do begin o = p.parse ARGV rescue Optimist::HelpNeeded buf = StringIO.new p.educate buf buf.rewind opts = { :animate => false, :duration => 12, :os => rand * 8192, :speed => 20, :spread => 8.0, :freq => 0.3 } Lol.cat buf, opts puts buf.close exit 1 end o end p.die :spread, "must be >= 0.1" if opts[:spread] < 0.1 p.die :duration, "must be >= 0.1" if opts[:duration] < 0.1 p.die :speed, "must be >= 0.1" if opts[:speed] < 0.1 opts[:os] = opts[:seed] opts[:os] = rand(256) if opts[:os] == 0 begin files = ARGV.empty? ? [:stdin] : ARGV[0..-1] files.each do |file| fd = $stdin if file == '-' or file == :stdin begin fd = File.open(file, "r") unless fd == $stdin if $stdout.tty? or opts[:force] Lol.cat fd, opts else if fd.tty? fd.each do |line| $stdout.write(line) end else IO.copy_stream(fd, $stdout) end end rescue Errno::ENOENT puts "lolcat: #{file}: No such file or directory" exit 1 rescue Errno::EACCES puts "lolcat: #{file}: Permission denied" exit 1 rescue Errno::EISDIR puts "lolcat: #{file}: Is a directory" exit 1 rescue Errno::ENXIO puts "lolcat: #{file}: Is not a regular file" exit 1 rescue Errno::EPIPE exit 1 end end rescue Interrupt end end end
ruby
BSD-3-Clause
f4cca5601ea57df2b5b3c98feea8ad05f4421039
2026-01-04T15:40:26.663979Z
false
ankane/chartkick
https://github.com/ankane/chartkick/blob/c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f/test/test_helper.rb
test/test_helper.rb
require "bundler/setup" Bundler.require(:default) require "minitest/autorun"
ruby
MIT
c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f
2026-01-04T15:40:24.593942Z
false
ankane/chartkick
https://github.com/ankane/chartkick/blob/c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f/test/chartkick_test.rb
test/chartkick_test.rb
require_relative "test_helper" class ChartkickTest < Minitest::Test include Chartkick::Helper def setup @data = [[34, 42], [56, 49]] @content_for = {} end def test_line_chart assert_chart line_chart(@data) end def test_pie_chart assert_chart pie_chart(@data) end def test_column_chart assert_chart column_chart(@data) end def test_bar_chart assert_chart bar_chart(@data) end def test_area_chart assert_chart area_chart(@data) end def test_scatter_chart assert_chart scatter_chart(@data) end def test_geo_chart assert_chart geo_chart(@data) end def test_timeline assert_chart timeline(@data) end def test_escape_data bad_data = "</script><script>alert('xss')</script>" assert_match "\\u003cscript\\u003e", column_chart(bad_data) refute_match "<script>alert", column_chart(bad_data) end def test_escape_options bad_options = {xss: "</script><script>alert('xss')</script>"} assert_match "\\u003cscript\\u003e", column_chart([], **bad_options) refute_match "<script>alert", column_chart([], **bad_options) end def test_options_not_mutated options = {id: "boom"} line_chart @data, **options assert_equal "boom", options[:id] end def test_deep_merge_different_inner_key global_option = {library: {backgroundColor: "#eee"}} local_option = {library: {title: "test"}} correct_merge = {library: {backgroundColor: "#eee", title: "test"}} assert_equal Chartkick::Utils.deep_merge(global_option, local_option), correct_merge end def test_deep_merge_same_inner_key global_option = {library: {backgroundColor: "#eee"}} local_option = {library: {backgroundColor: "#fff"}} correct_merge = {library: {backgroundColor: "#fff"}} assert_equal Chartkick::Utils.deep_merge(global_option, local_option), correct_merge end def test_id assert_match "id=\"test-id\"", line_chart(@data, id: "test-id") end def test_id_escaped assert_match "id=\"test-123&quot;\"", line_chart(@data, id: "test-123\"") end def test_height_pixels assert_match "height: 100px;", line_chart(@data, height: "100px") end def test_height_percent assert_match "height: 100%;", line_chart(@data, height: "100%") end def test_height_dot assert_match "height: 2.5rem;", line_chart(@data, height: "2.5rem") end def test_height_quote error = assert_raises(ArgumentError) do line_chart(@data, height: "150px\"") end assert_equal "Invalid height", error.message end def test_height_semicolon error = assert_raises(ArgumentError) do line_chart(@data, height: "150px;background:123") end assert_equal "Invalid height", error.message end def test_width_pixels assert_match "width: 100px;", line_chart(@data, width: "100px") end def test_width_percent assert_match "width: 100%;", line_chart(@data, width: "100%") end def test_width_dot assert_match "width: 2.5rem;", line_chart(@data, width: "2.5rem") end def test_width_quote error = assert_raises(ArgumentError) do line_chart(@data, width: "80%\"") end assert_equal "Invalid width", error.message end def test_width_semicolon error = assert_raises(ArgumentError) do line_chart(@data, width: "80%;background:123") end assert_equal "Invalid width", error.message end def test_loading assert_match ">Loading!!</div>", line_chart(@data, loading: "Loading!!") end def test_loading_escaped assert_match "&lt;b&gt;Loading!!&lt;/b&gt;", line_chart(@data, loading: "<b>Loading!!</b>") refute_match "<b>", line_chart(@data, loading: "<b>Loading!!</b>") end def test_nonce assert_match "<script nonce=\"test-123\">", line_chart(@data, nonce: "test-123") end def test_nonce_escaped assert_match "<script nonce=\"test-123&quot;\">", line_chart(@data, nonce: "test-123\"") end def test_defer assert_output(nil, /defer option is no longer needed/) do line_chart(@data, defer: true) end end def test_content_for refute_match "<script", line_chart(@data, content_for: :charts_js) assert_match "<script", @content_for[:charts_js] end def test_default_options Chartkick.options = {id: "test-123"} assert_match "id=\"test-123\"", line_chart(@data) ensure Chartkick.options = {} end def test_chart_ids @chartkick_chart_id = 0 3.times do |i| assert_match "chart-#{i + 1}", line_chart(@data) end end def test_chart_json assert_equal "[1,2,3]", [1, 2, 3].chart_json assert_equal %![{"name":"s1","data":[["t1",1],["t2",2]]}]!, {["s1", "t1"] => 1, ["s1", "t2"] => 2}.chart_json assert_equal %![{"name":"s1","data":[["t1",1],["t2",2]]}]!, [{name: "s1", data: {"t1" => 1, "t2" => 2}}].chart_json end def assert_chart(chart) assert_match "new Chartkick", chart end def content_for(value) @content_for[value] = yield end end
ruby
MIT
c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f
2026-01-04T15:40:24.593942Z
false
ankane/chartkick
https://github.com/ankane/chartkick/blob/c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f/lib/chartkick.rb
lib/chartkick.rb
# stdlib require "erb" require "json" # modules require_relative "chartkick/core_ext" require_relative "chartkick/helper" require_relative "chartkick/utils" require_relative "chartkick/version" # integrations require_relative "chartkick/engine" if defined?(Rails) require_relative "chartkick/sinatra" if defined?(Sinatra) if defined?(ActiveSupport.on_load) ActiveSupport.on_load(:action_view) do include Chartkick::Helper end end module Chartkick class << self attr_accessor :content_for attr_accessor :options end self.options = {} end
ruby
MIT
c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f
2026-01-04T15:40:24.593942Z
false
ankane/chartkick
https://github.com/ankane/chartkick/blob/c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f/lib/chartkick/sinatra.rb
lib/chartkick/sinatra.rb
require "sinatra/base" class Sinatra::Base helpers Chartkick::Helper end
ruby
MIT
c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f
2026-01-04T15:40:24.593942Z
false
ankane/chartkick
https://github.com/ankane/chartkick/blob/c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f/lib/chartkick/version.rb
lib/chartkick/version.rb
module Chartkick VERSION = "5.2.1" end
ruby
MIT
c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f
2026-01-04T15:40:24.593942Z
false
ankane/chartkick
https://github.com/ankane/chartkick/blob/c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f/lib/chartkick/core_ext.rb
lib/chartkick/core_ext.rb
# for both multiple series and # making sure hash order is preserved in JavaScript class Array def chart_json map do |v| if v.is_a?(Hash) && v[:data].is_a?(Hash) v = v.dup v[:data] = v[:data].to_a end v end.to_json end end class Hash def chart_json if (key = keys.first) && key.is_a?(Array) && key.size == 2 group_by { |k, _v| k[0] }.map do |name, data| {name: name, data: data.map { |k, v| [k[1], v] }} end else to_a end.to_json end end
ruby
MIT
c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f
2026-01-04T15:40:24.593942Z
false
ankane/chartkick
https://github.com/ankane/chartkick/blob/c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f/lib/chartkick/utils.rb
lib/chartkick/utils.rb
module Chartkick module Utils # https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/hash/deep_merge.rb def self.deep_merge(hash_a, hash_b) hash_a = hash_a.dup hash_b.each_pair do |k, v| tv = hash_a[k] hash_a[k] = tv.is_a?(Hash) && v.is_a?(Hash) ? deep_merge(tv, v) : v end hash_a end # from https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/string/output_safety.rb JSON_ESCAPE = { "&" => '\u0026', ">" => '\u003e', "<" => '\u003c', "\u2028" => '\u2028', "\u2029" => '\u2029' } JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/u def self.json_escape(s) if ERB::Util.respond_to?(:json_escape) ERB::Util.json_escape(s) else s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE) end end end end
ruby
MIT
c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f
2026-01-04T15:40:24.593942Z
false
ankane/chartkick
https://github.com/ankane/chartkick/blob/c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f/lib/chartkick/helper.rb
lib/chartkick/helper.rb
module Chartkick module Helper def line_chart(data_source, **options) chartkick_chart "LineChart", data_source, **options end def pie_chart(data_source, **options) chartkick_chart "PieChart", data_source, **options end def column_chart(data_source, **options) chartkick_chart "ColumnChart", data_source, **options end def bar_chart(data_source, **options) chartkick_chart "BarChart", data_source, **options end def area_chart(data_source, **options) chartkick_chart "AreaChart", data_source, **options end def scatter_chart(data_source, **options) chartkick_chart "ScatterChart", data_source, **options end def geo_chart(data_source, **options) chartkick_chart "GeoChart", data_source, **options end def timeline(data_source, **options) chartkick_chart "Timeline", data_source, **options end private # don't break out options since need to merge with default options def chartkick_chart(klass, data_source, **options) options = Chartkick::Utils.deep_merge(Chartkick.options, options) @chartkick_chart_id ||= 0 element_id = options.delete(:id) || "chart-#{@chartkick_chart_id += 1}" height = (options.delete(:height) || "300px").to_s width = (options.delete(:width) || "100%").to_s defer = !!options.delete(:defer) # content_for: nil must override default content_for = options.key?(:content_for) ? options.delete(:content_for) : Chartkick.content_for nonce = options.fetch(:nonce, true) options.delete(:nonce) if nonce == true # Secure Headers also defines content_security_policy_nonce but it takes an argument # Rails 5.2 overrides this method, but earlier versions do not if respond_to?(:content_security_policy_nonce) && (content_security_policy_nonce rescue nil) # Rails 5.2+ nonce = content_security_policy_nonce elsif respond_to?(:content_security_policy_script_nonce) # Secure Headers nonce = content_security_policy_script_nonce else nonce = nil end end nonce_html = nonce ? " nonce=\"#{ERB::Util.html_escape(nonce)}\"" : nil # html vars html_vars = { id: element_id, height: height, width: width, # don't delete loading option since it needs to be passed to JS loading: options[:loading] || "Loading..." } [:height, :width].each do |k| # limit to alphanumeric and % for simplicity # this prevents things like calc() but safety is the priority # dot does not need escaped in square brackets raise ArgumentError, "Invalid #{k}" unless /\A[a-zA-Z0-9%.]*\z/.match?(html_vars[k]) end html_vars.each_key do |k| # escape all variables # we already limit height and width above, but escape for safety as fail-safe # to prevent XSS injection in worse-case scenario html_vars[k] = ERB::Util.html_escape(html_vars[k]) end html = (options.delete(:html) || %(<div id="%{id}" style="height: %{height}; width: %{width}; text-align: center; color: #999; line-height: %{height}; font-size: 14px; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helvetica, sans-serif;">%{loading}</div>)) % html_vars # js vars js_vars = { type: klass.to_json, id: element_id.to_json, data: data_source.respond_to?(:chart_json) ? data_source.chart_json : data_source.to_json, options: options.to_json } js_vars.each_key do |k| js_vars[k] = Chartkick::Utils.json_escape(js_vars[k]) end createjs = "new Chartkick[%{type}](%{id}, %{data}, %{options});" % js_vars warn "[chartkick] The defer option is no longer needed and can be removed" if defer # Turbolinks preview restores the DOM except for painted <canvas> # since it uses cloneNode(true) - https://developer.mozilla.org/en-US/docs/Web/API/Node/ # # don't rerun JS on preview to prevent # 1. animation # 2. loading data from URL js = <<~JS <script#{nonce_html}> (function() { if (document.documentElement.hasAttribute("data-turbolinks-preview")) return; if (document.documentElement.hasAttribute("data-turbo-preview")) return; var createChart = function() { #{createjs} }; if ("Chartkick" in window) { createChart(); } else { window.addEventListener("chartkick:load", createChart, true); } })(); </script> JS if content_for content_for(content_for) { js.respond_to?(:html_safe) ? js.html_safe : js } else html += "\n#{js}" end html.respond_to?(:html_safe) ? html.html_safe : html end end end
ruby
MIT
c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f
2026-01-04T15:40:24.593942Z
false
ankane/chartkick
https://github.com/ankane/chartkick/blob/c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f/lib/chartkick/engine.rb
lib/chartkick/engine.rb
module Chartkick class Engine < ::Rails::Engine # for assets # for importmap initializer "chartkick.importmap" do |app| if app.config.respond_to?(:assets) && defined?(Importmap) && defined?(Sprockets) app.config.assets.precompile << "chartkick.js" app.config.assets.precompile << "Chart.bundle.js" end end end end
ruby
MIT
c2f50b9bf922a1df7beb8fb1b8a4990bb517a15f
2026-01-04T15:40:24.593942Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/features/support/env.rb
features/support/env.rb
# frozen_string_literal: true require "aruba" require "aruba/cucumber" require "aruba/processes/in_process" require "aruba/processes/spawn_process" require_relative "aruba_adapter" Before("@spawn") do aruba.config.command_launcher = :spawn gemfile_path = expand_path("Gemfile") set_environment_variable "BUNDLE_GEMFILE", File.expand_path(gemfile_path) set_environment_variable "RUBY_OPT", "-W0" set_environment_variable( "GUARD_NOTIFIERS", "---\n"\ "- :name: :file\n"\ " :options:\n"\ " :path: '/dev/stdout'\n" ) end Before("@in-process") do aruba.config.command_launcher = :in_process aruba.config.main_class = ArubaAdapter end Before do set_environment_variable "INSIDE_ARUBA_TEST", "1" home = expand_path("home") set_environment_variable "HOME", home FileUtils.mkdir(home) @aruba_timeout_seconds = Cucumber::JRUBY ? 45 : 15 end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/features/support/aruba_adapter.rb
features/support/aruba_adapter.rb
# frozen_string_literal: true require "guard/cli" require "guard/ui" # @private class ArubaAdapter def initialize(argv, stdin = STDIN, stdout = STDOUT, stderr = STDERR, kernel = Kernel) @argv = argv @stdin = stdin @stdout = stdout @stderr = stderr @kernel = kernel if ENV["INSIDE_ARUBA_TEST"] == "1" Guard::UI.options = Guard::UI.options.merge(flush_seconds: 0) end end def execute! exit_code = execute # Proxy our exit code back to the injected kernel. @kernel.exit(exit_code) end def execute # Thor accesses these streams directly rather than letting # them be injected, so we replace them... $stderr = @stderr $stdin = @stdin $stdout = @stdout # Run our normal Thor app the way we know and love. Guard::CLI.start(@argv) # Thor::Base#start does not have a return value, assume # success if no exception is raised. 0 rescue StandardError => e # The ruby interpreter would pipe this to STDERR and exit 1 in the case # of an unhandled exception backtrace = e.backtrace @stderr.puts "#{backtrace.shift}: #{e.message} (#{e.class})" @stderr.puts backtrace.map { |line| "\tfrom #{line}" }.join("\n") 1 rescue SystemExit => e e.status ensure # flush the logger so the output doesn't appear in next CLI invocation logger = Guard::UI.logger logger.flush logger.close Guard::UI.reset # ...then we put them back. $stderr = STDERR $stdin = STDIN $stdout = STDOUT end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/features/step_definitions/guard_steps.rb
features/step_definitions/guard_steps.rb
# frozen_string_literal: true Given(/^my Guardfile contains:$/) do |contents| write_file("Guardfile", contents) end Given(/^my Rakefile contains:$/) do |contents| write_file("Rakefile", contents) end Given(/^my Gemfile includes "([^"]*)"$/) do |gem| (@gems ||= []) << gem end Given(/^Guard is bundled using source$/) do gems = @gems || [] gems << "gem 'guard', path: File.expand_path(File.join(Dir.pwd, '..', '..'))" write_file("Gemfile", "#{gems.join("\n")}\n") run_command_and_stop("bundle install --quiet", fail_on_error: true) end When(/^I start `([^`]*)`$/) do |cmd| skip_this_scenario if defined?(JRUBY_VERSION) @interactive = run_command(cmd) step "I wait for Guard to become idle" end When(/^I create a file "([^"]*)"$/) do |path| write_file(path, "") # give guard time to respond to change type(+"sleep 1") end When(/^I append to the file "([^"]*)"$/) do |path| append_to_file(path, "modified") # give guard time to respond to change type(+"sleep 1") end When(/^I stop guard$/) do close_input end When(/^I wait for Guard to become idle$/) do expected = "guard(main)>" begin Timeout.timeout(aruba.config.exit_timeout) do loop do break if last_command_started.stdout.include?(expected) sleep 0.1 end end rescue Timeout::Error warn all_commands.map(&:stdout).join("\n") warn all_commands.map(&:stderr).join("\n") fail end end When(/^I type in "([^"]*)"$/) do |line| type line end When(/^I press Ctrl-C$/) do skip_this_scenario if Nenv.ci? # Probably needs to be fixed on Windows obj = @interactive.instance_variable_get(:@delegate_sd_obj) pid = obj.instance_variable_get(:@process).pid Process.kill("SIGINT", pid) step "I wait for Guard to become idle" end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/spec_helper.rb
spec/spec_helper.rb
# frozen_string_literal: true # This file was generated by the `rspec --init` command. Conventionally, all # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. # The generated `.rspec` file contains `--require spec_helper` which will cause # this file to always be loaded, without a need to explicitly require it in any # files. # # Given that it is always loaded, you are encouraged to keep this file as # light-weight as possible. Requiring heavyweight dependencies from this file # will add to the boot time of your test suite on EVERY test run, even for an # individual file that may not need all of that loaded. Instead, consider making # a separate helper file that requires the additional dependencies and performs # the additional setup, and require it from the spec files that actually need # it. # # The `.rspec` file also contains a few flags that are not defaults but that # users commonly want. # require "fileutils" if ENV["CI"] require "simplecov" SimpleCov.start do add_filter "/spec" end require "codecov" SimpleCov.formatter = SimpleCov::Formatter::Codecov end ENV["GUARD_SPECS_RUNNING"] = "1" path = "#{File.expand_path(__dir__)}/support/**/*.rb" Dir[path].sort.each { |f| require f } def stub_guardfile(contents = nil, &block) stub_file("Guardfile", contents, &block) end def stub_guardfile_rb(contents = nil, &block) stub_file("guardfile.rb", contents, &block) end def stub_user_guardfile(contents = nil, &block) stub_file("~/.Guardfile", contents, &block) end def stub_user_guard_rb(contents = nil, &block) stub_file("~/.guard.rb", contents, &block) end def stub_user_project_guardfile(contents = nil, &block) stub_file(".Guardfile", contents, &block) end def stub_file(path, contents = nil, &block) exists = !!contents pathname = instance_double(Pathname) allow(Pathname).to receive(:new).with(path).and_return(pathname) allow(pathname).to receive(:to_s).and_return(path) allow(pathname).to receive(:expand_path).and_return(pathname) allow(pathname).to receive(:exist?).and_return(exists) if exists if block allow(pathname).to receive(:read) do yield end else allow(pathname).to receive(:read).and_return(contents) end else allow(pathname).to receive(:read) do fail Errno::ENOENT end end pathname end # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration RSpec.configure do |config| # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. # These two settings work together to allow you to limit a spec run # to individual examples or groups you care about by tagging them with # `:focus` metadata. When nothing is tagged with `:focus`, all examples # get run. # config.filter_run :focus config.filter_run focus: ENV["CI"] != "true" config.run_all_when_everything_filtered = true # Limits the available syntax to the non-monkey patched syntax that is # recommended. # # For more details, see: # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching config.disable_monkey_patching! # This setting enables warnings. It's recommended, but in some cases may # be too noisy due to issues in dependencies. # config.warnings = true # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). # # This is set in .rspec file # config.default_formatter = "doc" end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. # config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed config.raise_errors_for_deprecations! config.mock_with :rspec do |mocks| mocks.verify_doubled_constant_names = true mocks.verify_partial_doubles = true end config.before(:each, :stub_ui) do if Guard.const_defined?("UI") && Guard::UI.respond_to?(:info) # Stub all UI methods, so no visible output appears for the UI class allow(Guard::UI).to receive(:info) allow(Guard::UI).to receive(:warning) allow(Guard::UI).to receive(:error) allow(Guard::UI).to receive(:debug) allow(Guard::UI).to receive(:deprecation) allow(Guard::UI).to receive(:reset_and_clear) end end end RSpec.shared_context "with testing plugins" do before do Guard::Dummy = Class.new(Guard::Plugin) do def throwing throw :task_has_failed end def failing fail "I break your system" end def run_on_changes(_paths); "I'm a success"; end def run_on_change(_paths); end def run_on_modifications(_paths); end def run_on_additions(_paths); end def run_on_removals(_paths); end def run_on_deletion(_paths); end end Guard::Doe = Class.new(Guard::Plugin) Guard::FooBar = Class.new(Guard::Plugin) Guard::FooBaz = Class.new(Guard::Plugin) end after do Guard.__send__(:remove_const, :Dummy) Guard.__send__(:remove_const, :Doe) Guard.__send__(:remove_const, :FooBar) Guard.__send__(:remove_const, :FooBaz) end end RSpec.shared_context "Guard options" do let(:inline_guardfile) { "guard :dummy" } let(:base_options) { { watchdirs: Dir.pwd, inline: inline_guardfile, no_interactions: true } } let(:options) { base_options } end RSpec.shared_context "with engine" do require "guard/engine" require "guard/plugin" include_context "Guard options" include_context "with testing plugins" let(:engine) { Guard::Engine.new(options) } let(:interactor) do instance_double( "Guard::Interactor", interactive: true, "options=": true, foreground: :exit, background: true, handle_interrupt: true ) end let(:listener) { instance_double("Listen::Listener", ignore: true, ignore!: true, start: true, stop: true) } let(:session) { engine.session } let(:groups) { engine.groups } let(:plugins) { engine.plugins } before do # Stub classes with side-effects allow(Guard::Interactor).to receive(:new).and_return(interactor) allow(Listen).to receive(:to).and_return(listener) end end RSpec.shared_context "with fake pry" do let(:output) { double } before do Thread.current[:engine] = engine class FakePry < Pry::Command def self.output; end end end after do Object.__send__(:remove_const, :FakePry) Thread.current[:engine] = nil end before do allow(FakePry).to receive(:output).and_return(output) end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/support/gems_helper.rb
spec/support/gems_helper.rb
# frozen_string_literal: true def growl_installed? require "growl" true rescue LoadError false end def libnotify_installed? require "libnotify" true rescue LoadError false end def rbnotifu_installed? require "rb-notifu" true rescue LoadError false end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/support/platform_helper.rb
spec/support/platform_helper.rb
# frozen_string_literal: true def mac? RbConfig::CONFIG["target_os"] =~ /darwin/i end def linux? RbConfig::CONFIG["target_os"] =~ /linux/i end def windows? RbConfig::CONFIG["target_os"] =~ /mswin|mingw/i end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/group_spec.rb
spec/lib/guard/group_spec.rb
# frozen_string_literal: true require "guard/group" RSpec.describe Guard::Group do subject { described_class.new(name, options) } let(:name) { :foo } let(:options) { {} } describe "#name" do specify { expect(subject.name).to eq :foo } context "when initialized from a string" do let(:name) { "foo" } specify { expect(subject.name).to eq :foo } end end describe "#options" do context "when provided" do let(:options) { { halt_on_fail: true } } specify { expect(subject.options).to eq options } end end describe "#title" do specify { expect(subject.title).to eq "Foo" } end describe "#to_s" do specify do expect(subject.to_s).to eq "#<Guard::Group @name=foo @options={}>" end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/terminal_spec.rb
spec/lib/guard/terminal_spec.rb
# frozen_string_literal: true require "guard/terminal" RSpec.describe Guard::Terminal do subject { described_class } it { is_expected.to respond_to(:clear) } let(:sheller) { class_double("Shellany::Sheller") } before do stub_const("Shellany::Sheller", sheller) end describe ".clear" do context "when on UNIX" do before { allow(Gem).to receive(:win_platform?).and_return(false) } context "when the clear command exists" do let(:result) { [double(success?: true), "\e[H\e[2J", ""] } it "clears the screen using 'clear'" do expect(sheller).to receive(:system).with("printf '\33c\e[3J';") .and_return(result) ::Guard::Terminal.clear end end context "when the clear command fails" do let(:result) { [double(success?: false), nil, 'Guard failed to run "clear;"'] } before do allow(sheller).to receive(:system).with("printf '\33c\e[3J';") .and_return(result) end it "fails" do expect { ::Guard::Terminal.clear } .to raise_error(Errno::ENOENT, /Guard failed to run "clear;"/) end end end context "when on Windows" do before { allow(Gem).to receive(:win_platform?).and_return(true) } it "clears the screen" do result = [double(success?: true), "\f", ""] expect(sheller).to receive(:system).with("cls").and_return(result) ::Guard::Terminal.clear end context "when the clear command fails" do let(:result) { [double(success?: false), nil, 'Guard failed to run "cls"'] } before do allow(sheller).to receive(:system).with("cls").and_return(result) end it "fails" do expect { ::Guard::Terminal.clear } .to raise_error(Errno::ENOENT, /Guard failed to run "cls"/) end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/notifier_spec.rb
spec/lib/guard/notifier_spec.rb
# frozen_string_literal: true require "guard/notifier" RSpec.describe Guard::Notifier, :stub_ui do subject { described_class } let(:notifier) { instance_double("Notiffany::Notifier") } before do allow(Notiffany::Notifier).to receive(:new).and_return(notifier) end after do Guard::Notifier.instance_variable_set(:@notifier, nil) end describe "toggle_notification" do before do allow(notifier).to receive(:enabled?).and_return(true) end context "with available notifiers" do context "when currently on" do before do allow(notifier).to receive(:active?).and_return(true) subject.connect end it "suspends notifications" do expect(notifier).to receive(:turn_off) subject.toggle end end context "when currently off" do before do subject.connect allow(notifier).to receive(:active?).and_return(false) end it "resumes notifications" do expect(notifier).to receive(:turn_on) subject.toggle end end end end describe ".notify" do before do subject.connect allow(notifier).to receive(:notify) end context "with no options" do it "notifies" do expect(notifier).to receive(:notify).with("A", {}) subject.notify("A") end end context "with multiple parameters" do it "notifies" do expect(notifier).to receive(:notify) .with("A", priority: 2, image: :failed) subject.notify("A", priority: 2, image: :failed) end end context "with a runtime error" do before do allow(notifier).to receive(:notify).and_raise(RuntimeError, "an error") end it "shows an error" do expect(Guard::UI).to receive(:error) .with(/Notification failed for .+: an error/) subject.notify("A", priority: 2, image: :failed) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/interactor_spec.rb
spec/lib/guard/interactor_spec.rb
# frozen_string_literal: true require "guard/interactor" RSpec.describe Guard::Interactor, :stub_ui do include_context "with engine" let(:interactive) { true } subject { described_class.new(engine, interactive) } let!(:pry_interactor) { instance_double("Guard::Jobs::PryWrapper", foreground: true, background: true) } let!(:sleep_interactor) { instance_double("Guard::Jobs::Sleep", foreground: true, background: true) } before do allow(Guard::Interactor).to receive(:new).and_call_original allow(Guard::Jobs::PryWrapper).to receive(:new).with(engine, {}).and_return(pry_interactor) allow(Guard::Jobs::Sleep).to receive(:new).with(engine, {}).and_return(sleep_interactor) end describe "#enabled & #enabled=" do it "returns true by default" do expect(subject).to be_interactive end context "interactor not enabled" do before { subject.interactive = false } it "returns false" do expect(subject).to_not be_interactive end end end describe "#options & #options=" do before { subject.options = nil } it "returns {} by default" do expect(subject.options).to eq({}) end context "options set to { foo: :bar }" do before { subject.options = { foo: :bar } } it "returns { foo: :bar }" do expect(subject.options).to eq(foo: :bar) end end context "options set after interactor is instantiated" do it "set the options and initialize a new interactor job" do subject.foreground expect(Guard::Jobs::PryWrapper).to receive(:new).with(engine, foo: :bar).and_return(pry_interactor) subject.options = { foo: :bar } subject.foreground end end end context "when enabled" do before { subject.interactive = true } describe "#foreground" do it "starts Pry" do expect(pry_interactor).to receive(:foreground) subject.foreground end end describe "#background" do it "hides Pry" do # Eager-init the job subject.foreground expect(pry_interactor).to receive(:background) subject.background end end describe "#handle_interrupt" do it "interrupts Pry" do expect(pry_interactor).to receive(:handle_interrupt) subject.handle_interrupt end end end context "when disabled" do before { subject.interactive = false } describe "#foreground" do it "sleeps" do expect(sleep_interactor).to receive(:foreground) subject.foreground end end describe "#background" do it "wakes up from sleep" do # Eager-init the job subject.foreground expect(sleep_interactor).to receive(:background) subject.background end end describe "#handle_interrupt" do it "interrupts sleep" do expect(sleep_interactor).to receive(:handle_interrupt) subject.handle_interrupt end end end describe "job selection" do before do subject.interactive = dsl_enabled end context "when enabled from the DSL" do let(:dsl_enabled) { true } context "when enabled from the commandline" do let(:interactive) { true } it "uses only pry" do expect(Guard::Jobs::PryWrapper).to receive(:new) expect(Guard::Jobs::Sleep).to_not receive(:new) subject.foreground end it { is_expected.to be_interactive } end context "when disabled from the commandline" do let(:interactive) { false } it "uses only sleeper" do expect(Guard::Jobs::PryWrapper).to receive(:new) expect(Guard::Jobs::Sleep).to_not receive(:new) subject.foreground end it { is_expected.to be_interactive } end end context "when disabled from the DSL" do let(:dsl_enabled) { false } context "when enabled from the commandline" do it "uses only sleeper" do expect(Guard::Jobs::PryWrapper).to_not receive(:new) expect(Guard::Jobs::Sleep).to receive(:new) subject.foreground end it { is_expected.to_not be_interactive } end context "when disabled from the commandline" do let(:interactive) { false } it "uses only sleeper" do expect(Guard::Jobs::PryWrapper).to_not receive(:new) expect(Guard::Jobs::Sleep).to receive(:new) subject.foreground end it { is_expected.to_not be_interactive } end end end context "when first enabled, then disabled" do it "uses only sleeper" do expect(Guard::Jobs::PryWrapper).to receive(:new) subject.foreground subject.interactive = false expect(Guard::Jobs::Sleep).to receive(:new) subject.foreground end end context "when first disabled, then enabled" do let(:interactive) { false } it "uses only sleeper" do expect(Guard::Jobs::Sleep).to receive(:new) subject.foreground subject.interactive = true expect(Guard::Jobs::PryWrapper).to receive(:new) subject.foreground end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/plugin_util_spec.rb
spec/lib/guard/plugin_util_spec.rb
# frozen_string_literal: true require "guard/plugin_util" RSpec.describe Guard::PluginUtil, :stub_ui do let(:evaluator) { instance_double("Guard::Guardfile::Evaluator", evaluate: true, guardfile_include?: false) } describe ".plugin_names" do before do spec = Gem::Specification gems = [ instance_double(spec, name: "guard-myplugin"), instance_double(spec, name: "gem1", full_gem_path: "/gem1"), instance_double(spec, name: "gem2", full_gem_path: "/gem2"), instance_double(spec, name: "guard-compat") ] allow(File).to receive(:exist?) .with("/gem1/lib/guard/gem1.rb") { false } allow(File).to receive(:exist?) .with("/gem2/lib/guard/gem2.rb") { true } gem = class_double(Gem::Specification) stub_const("Gem::Specification", gem) expect(Gem::Specification).to receive(:find_all) { gems } allow(Gem::Specification).to receive(:unresolved_deps) { [] } end it "returns the list of guard gems" do expect(described_class.plugin_names).to include("myplugin") end it "returns the list of embedded guard gems" do expect(described_class.plugin_names).to include("gem2") end it "ignores guard-compat" do expect(described_class.plugin_names).to_not include("compat") end end describe "#initialize" do it "accepts a name without guard-" do expect(described_class.new("dummy", evaluator: evaluator).name).to eq "dummy" end it "accepts a name with guard-" do expect(described_class.new("guard-dummy", evaluator: evaluator).name).to eq "dummy" end end describe "#initialize_plugin" do let(:plugin_util) { described_class.new("dummy", evaluator: evaluator) } let(:dummy) { stub_const("Guard::Dummy", double) } context "with a plugin inheriting from Guard::Plugin" do it "instantiate the plugin using the new API" do options = { watchers: ["watcher"], group: "foo" } expect(dummy).to receive(:new).with(options) plugin_util.initialize_plugin(options) end end end describe "#plugin_location" do subject { described_class.new("dummy", evaluator: evaluator) } it "returns the path of a Guard gem" do expect(Gem::Specification).to receive(:find_by_name) .with("guard-dummy") { double(full_gem_path: "gems/guard-dummy") } expect(subject.plugin_location).to eq "gems/guard-dummy" end end describe "#plugin_class" do it "reports an error if the class is not found" do expect(::Guard::UI).to receive(:error).with(/Could not load/) plugin = described_class.new("notAGuardClass", evaluator: evaluator) allow(plugin).to receive(:require).with("guard/notaguardclass") .and_raise(LoadError, "cannot load such file --") expect { plugin.plugin_class }.to raise_error(LoadError) end context "with a nested Guard class" do it "resolves the Guard class from string" do plugin = described_class.new("classname", evaluator: evaluator) expect(plugin).to receive(:require).with("guard/classname") do stub_const("Guard::Classname", double) end expect(plugin.plugin_class).to eq Guard::Classname end it "resolves the Guard class from symbol" do plugin = described_class.new(:classname, evaluator: evaluator) expect(plugin).to receive(:require).with("guard/classname") do stub_const("Guard::Classname", double) end expect(plugin.plugin_class).to eq Guard::Classname end end context "with a name with dashes" do it "returns the Guard class" do plugin = described_class.new("dashed-class-name", evaluator: evaluator) expect(plugin).to receive(:require).with("guard/dashed-class-name") do stub_const("Guard::DashedClassName", double) end expect(plugin.plugin_class).to eq Guard::DashedClassName end end context "with a name with underscores" do it "returns the Guard class" do plugin = described_class.new("underscore_class_name", evaluator: evaluator) expect(plugin).to receive(:require).with("guard/underscore_class_name") do stub_const("Guard::UnderscoreClassName", double) end expect(plugin.plugin_class).to eq Guard::UnderscoreClassName end end context "with a name like VSpec" do it "returns the Guard class" do plugin = described_class.new("vspec", evaluator: evaluator) expect(plugin).to receive(:require).with("guard/vspec") do stub_const("Guard::VSpec", double) end expect(plugin.plugin_class).to eq Guard::VSpec end end context "with an inline Guard class" do it "returns the Guard class" do plugin = described_class.new("inline", evaluator: evaluator) stub_const("Guard::Inline", double) expect(plugin).to_not receive(:require) expect(plugin.plugin_class).to eq Guard::Inline end end end describe "#add_to_guardfile" do context "when the Guard is already in the Guardfile" do before do allow(evaluator).to receive(:guardfile_include?) { true } end it "shows an info message" do expect(::Guard::UI).to receive(:info) .with "Guardfile already includes myguard guard" described_class.new("myguard", evaluator: evaluator).add_to_guardfile end end context "when Guardfile is empty" do let(:plugin_util) { described_class.new("myguard", evaluator: evaluator) } let(:plugin_class) { class_double("Guard::Plugin") } let(:location) { "/Users/me/projects/guard-myguard" } let(:gem_spec) { instance_double("Gem::Specification") } let(:io) { StringIO.new } before do allow(gem_spec).to receive(:full_gem_path).and_return(location) allow(evaluator).to receive(:guardfile_include?) { false } allow(Guard).to receive(:constants).and_return([:MyGuard]) allow(Guard).to receive(:const_get).with(:MyGuard) .and_return(plugin_class) allow(Gem::Specification).to receive(:find_by_name) .with("guard-myguard").and_return(gem_spec) allow(plugin_class).to receive(:template).with(location) .and_return("Template content") allow(File).to receive(:read).with("Guardfile") { "Guardfile content" } allow(File).to receive(:open).with("Guardfile", "wb").and_yield io end it "appends the template to the Guardfile" do plugin_util.add_to_guardfile expect(io.string).to eq "Guardfile content\n\nTemplate content\n" end end context "when the Guard is not in the Guardfile" do let(:plugin_util) { described_class.new("myguard", evaluator: evaluator) } let(:plugin_class) { class_double("Guard::Plugin") } let(:location) { "/Users/me/projects/guard-myguard" } let(:gem_spec) { instance_double("Gem::Specification") } let(:io) { StringIO.new } before do allow(gem_spec).to receive(:full_gem_path).and_return(location) allow(evaluator).to receive(:guardfile_include?) { false } allow(Guard).to receive(:constants).and_return([:MyGuard]) allow(Guard).to receive(:const_get).with(:MyGuard) .and_return(plugin_class) allow(Gem::Specification).to receive(:find_by_name) .with("guard-myguard").and_return(gem_spec) allow(plugin_class).to receive(:template).with(location) .and_return("Template content") allow(File).to receive(:read).with("Guardfile") { "Guardfile content" } allow(File).to receive(:open).with("Guardfile", "wb").and_yield io end it "appends the template to the Guardfile" do plugin_util.add_to_guardfile expect(io.string).to eq "Guardfile content\n\nTemplate content\n" end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/watcher_spec.rb
spec/lib/guard/watcher_spec.rb
# frozen_string_literal: true require "guard/watcher" require "guard/plugin" RSpec.describe Guard::Watcher, :stub_ui do let(:args) { [] } subject { described_class.new(*args) } describe "#initialize" do context "with no arguments" do let(:args) { [] } it "raises an error" do expect { subject }.to raise_error(ArgumentError) end end context "with a pattern parameter" do let(:pattern) { ["spec_helper.rb"] } let(:args) { [pattern] } it "creates a matcher" do expect(described_class::Pattern).to receive(:create).with(pattern) subject end end end describe "#action" do it "sets the action to nothing by default" do expect(described_class.new(/spec_helper\.rb/).action).to be_nil end it "sets the action to the supplied block" do action = ->(m) { "spec/#{m[1]}_spec.rb" } expect(described_class.new(%r{^lib/(.*).rb}, action).action).to eq action end end describe "#==" do it "returns true for equal watchers" do expect(described_class.new(/spec_helper\.rb/)) .to eq(described_class.new(/spec_helper\.rb/)) end it "returns false for unequal watchers" do expect(described_class.new(/spec_helper\.rb/)) .not_to eq(described_class.new(/spec_helper\.r/)) end end describe ".match_files" do let(:plugin) { instance_double("Guard::Plugin", options: {}) } def matched(files) described_class.match_files(plugin, files) end context "without a watcher action" do before do allow(plugin).to receive(:watchers) .and_return([described_class.new(pattern)]) end context "with a regex pattern" do let(:pattern) { /.*_spec\.rb/ } it "returns the paths that matches the regex" do expect(matched(%w[foo_spec.rb foo.rb])).to eq %w[foo_spec.rb] end end context "with a string pattern" do let(:pattern) { "foo_spec.rb" } it "returns the path that matches the string" do expect(matched(%w[foo_spec.rb foo.rb])).to eq ["foo_spec.rb"] end end end context "with a watcher action without parameter" do context "for a watcher that matches file strings" do before do klass = described_class allow(plugin).to receive(:watchers).and_return( [ klass.new("spec_helper.rb", -> { "spec" }), klass.new("addition.rb", -> { 1 + 1 }), klass.new("hash.rb", -> { Hash[:foo, "bar"] }), klass.new("array.rb", -> { %w[foo bar] }), klass.new("blank.rb", -> { "" }), klass.new(/^uptime\.rb/, -> { "" }) ] ) end it "returns a single file specified within the action" do expect(matched(%w[spec_helper.rb])).to eq ["spec"] end it "returns multiple files specified within the action" do expect(matched(%w[hash.rb])).to eq %w[foo bar] end it "combines files from results of different actions" do expect(matched(%w[spec_helper.rb array.rb])).to eq %w[spec foo bar] end context "when action returns non-string or array of non-strings" do it "returns nothing" do expect(matched(%w[addition.rb])).to eq [] end end it "returns nothing if the action response is empty" do expect(matched(%w[blank.rb])).to eq [] end it "returns nothing if the action returns nothing" do expect(matched(%w[uptime.rb])).to eq [] end end context "for a watcher that matches information objects" do before do allow(plugin).to receive(:options).and_return(any_return: true) klass = described_class allow(plugin).to receive(:watchers).and_return( [ klass.new("spec_helper.rb", -> { "spec" }), klass.new("addition.rb", -> { 1 + 1 }), klass.new("hash.rb", -> { Hash[:foo, "bar"] }), klass.new("array.rb", -> { %w[foo bar] }), klass.new("blank.rb", -> { "" }), klass.new(/^uptime\.rb/, -> { "" }) ] ) end it "returns a single file specified within the action" do expect(matched(%w[spec_helper.rb]).class).to be Array expect(matched(%w[spec_helper.rb])).to_not be_empty end it "returns multiple files specified within the action" do expect(matched(%w[hash.rb])).to eq [{ foo: "bar" }] end it "combines the results of different actions" do expect(matched(%w[spec_helper.rb array.rb])) .to eq ["spec", %w[foo bar]] end it "returns the evaluated addition argument in an array" do expect(matched(%w[addition.rb]).class).to be(Array) expect(matched(%w[addition.rb])[0]).to eq 2 end it "returns nothing if the action response is empty string" do expect(matched(%w[blank.rb])).to eq [""] end it "returns nothing if the action returns empty string" do expect(matched(%w[uptime.rb])).to eq [""] end end end context "with a watcher action that takes a parameter" do context "for a watcher that matches file strings" do before do klass = described_class allow(plugin).to receive(:watchers).and_return [ klass.new(%r{lib/(.*)\.rb}, ->(m) { "spec/#{m[1]}_spec.rb" }), klass.new(/addition(.*)\.rb/, ->(_m) { 1 + 1 }), klass.new("hash.rb", ->(_m) { Hash[:foo, "bar"] }), klass.new(/array(.*)\.rb/, ->(_m) { %w[foo bar] }), klass.new(/blank(.*)\.rb/, ->(_m) { "" }), klass.new(/^uptime\.rb/, -> { "" }) ] end it "returns a substituted single file specified within the action" do expect(matched(%w[lib/foo.rb])).to eq ["spec/foo_spec.rb"] end it "returns multiple files specified within the action" do expect(matched(%w[hash.rb])).to eq %w[foo bar] end it "combines results of different actions" do expect(matched(%w[lib/foo.rb array.rb])) .to eq %w[spec/foo_spec.rb foo bar] end it "returns nothing if action returns non-string or non-string array" do expect(matched(%w[addition.rb])).to eq [] end it "returns nothing if the action response is empty" do expect(matched(%w[blank.rb])).to eq [] end it "returns nothing if the action returns nothing" do expect(matched(%w[uptime.rb])).to eq [] end end context "for a watcher that matches information objects" do before do allow(plugin).to receive(:options).and_return(any_return: true) kl = described_class allow(plugin).to receive(:watchers).and_return( [ kl.new(%r{lib/(.*)\.rb}, ->(m) { "spec/#{m[1]}_spec.rb" }), kl.new(/addition(.*)\.rb/, ->(m) { (1 + 1).to_s + m[0] }), kl.new("hash.rb", ->(m) { { foo: "bar", file_name: m[0] } }), kl.new(/array(.*)\.rb/, ->(m) { ["foo", "bar", m[0]] }), kl.new(/blank(.*)\.rb/, ->(_m) { "" }), kl.new(/^uptime\.rb/, -> { "" }) ] ) end it "returns a substituted single file specified within the action" do expect(matched(%w[lib/foo.rb])).to eq %w[spec/foo_spec.rb] end it "returns a hash specified within the action" do expect(matched(%w[hash.rb])).to eq [ { foo: "bar", file_name: "hash.rb" } ] end it "combinines results of different actions" do expect(matched(%w[lib/foo.rb array.rb])) .to eq ["spec/foo_spec.rb", %w[foo bar array.rb]] end it "returns the evaluated addition argument + the path" do expect(matched(%w[addition.rb])).to eq ["2addition.rb"] end it "returns nothing if the action response is empty string" do expect(matched(%w[blank.rb])).to eq [""] end it "returns nothing if the action returns is IO::NULL" do expect(matched(%w[uptime.rb])).to eq [""] end end end context "with an exception that is raised" do before do allow(plugin).to receive(:watchers).and_return( [described_class.new("evil.rb", -> { fail "EVIL" })] ) end it "displays the error and backtrace" do expect(Guard::UI).to receive(:error) do |msg| expect(msg).to include("Problem with watch action!") expect(msg).to include("EVIL") end described_class.match_files(plugin, ["evil.rb"]) end end context "for ambiguous watchers" do before do expect(plugin).to receive(:watchers).and_return [ described_class.new("awesome_helper.rb", -> {}), described_class.new(/.+some_helper.rb/, -> { "foo.rb" }), described_class.new(/.+_helper.rb/, -> { "bar.rb" }) ] end context "when the :first_match option is turned off" do before do allow(plugin).to receive(:options).and_return(first_match: false) end it "returns multiple files by combining the results of the watchers" do expect(described_class.match_files(plugin, ["awesome_helper.rb"])).to eq(["foo.rb", "bar.rb"]) end end context "when the :first_match option is turned on" do before do plugin.options[:first_match] = true end it "returns only the files from the first watcher" do expect(described_class.match_files(plugin, ["awesome_helper.rb"])).to eq(["foo.rb"]) end end end end describe "#match" do subject { described_class.new(pattern).match(file) } let(:matcher) { instance_double(described_class::Pattern::Matcher) } let(:match) { instance_double(described_class::Pattern::MatchResult) } before do allow(described_class::Pattern).to receive(:create).with(pattern) .and_return(matcher) allow(matcher).to receive(:match).with(pattern) .and_return(match_data) allow(described_class::Pattern::MatchResult).to receive(:new) .with(match_data, file).and_return(match) end context "with a valid pattern" do let(:pattern) { "foo.rb" } context "with a valid file name to match" do let(:file) { "foo.rb" } context "when matching is successful" do let(:match_data) { double("match data", to_a: ["foo"]) } it "returns the match result" do expect(subject).to be(match) end end context "when matching is not successful" do let(:match_data) { nil } it "returns nil" do expect(subject).to be_nil end end end end end describe "integration" do describe "#match" do subject { described_class.new(pattern) } context "with a named regexp pattern" do let(:pattern) { /(?<foo>.*)_spec\.rb/ } context "with a watcher that matches a file" do specify do expect(subject.match("bar_spec.rb")[0]).to eq("bar_spec.rb") expect(subject.match("bar_spec.rb")[1]).to eq("bar") end it "provides the match by name" do expect(subject.match("bar_spec.rb")[:foo]).to eq("bar") end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/dsl_spec.rb
spec/lib/guard/dsl_spec.rb
# frozen_string_literal: true require "guard/dsl" RSpec.describe Guard::Dsl do describe "#notification" do it "stores notification as a hash when :off is passed" do subject.notification(:off) expect(subject.result.notification).to eq(off: {}) end it "stores notification as a hash" do options = { foo: :bar } subject.notification(:notifier, options) expect(subject.result.notification).to eq(notifier: options) end end describe "#interactor" do it "stores interactor as a hash" do hash = { foo: :bar } subject.interactor(hash) expect(subject.result.interactor).to eq(hash) end end describe "#group" do it "stores groups as a hash" do options = { foo: :bar } subject.group(:frontend, options) { subject.guard(:foo) } subject.group(:backend, options) { subject.guard(:foo) } expect(subject.result.groups).to eq({ default: {}, frontend: options, backend: options }) end end describe "#guard" do it "stores plugins as a hash" do options1 = { opt1: :bar } options2 = { opt2: :baz } subject.group(:frontend) { subject.guard(:foo, options1) } subject.guard(:foo, options2) plugin_options1 = options1.merge(callbacks: [], watchers: [], group: :frontend) plugin_options2 = options2.merge(callbacks: [], watchers: [], group: :default) expect(subject.result.plugins).to eq([[:foo, plugin_options1], [:foo, plugin_options2]]) end end describe "#ignore" do it "stores ignore as a hash" do regex = /foo/ subject.ignore(regex) expect(subject.result.ignore).to eq([regex]) end end describe "#ignore_bang" do it "stores ignore_bang as a hash" do regex = /foo/ subject.ignore!(regex) expect(subject.result.ignore_bang).to eq([regex]) end end describe "#logger" do it "stores logger as a hash" do hash = { foo: :bar } subject.logger(hash) expect(subject.result.logger).to eq(hash) end end describe "#scopes" do it "stores scopes as a hash" do hash = { foo: :bar } subject.scope(hash) expect(subject.result.scopes).to eq(hash) end end describe "#directories" do it "stores directories as a hash when given as a string" do string = "lib" subject.directories(string) expect(subject.result.directories).to eq([string]) end it "stores directories as a hash when given as an array" do array = %w[bin lib] subject.directories(array) expect(subject.result.directories).to eq(array) end end describe "#clearing=" do it "stores clearing as a true when :on" do subject.clearing(:on) expect(subject.result.clearing).to eq(true) end it "stores clearing as a false otherwise" do subject.clearing(:off) expect(subject.result.clearing).to eq(false) end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/ui_spec.rb
spec/lib/guard/ui_spec.rb
# frozen_string_literal: true require "guard/ui" RSpec.describe Guard::UI do include_context "with engine" let(:logger) { instance_double("Lumberjack::Logger") } let(:terminal) { class_double("Guard::Terminal") } before do described_class.reset stub_const("Guard::Terminal", terminal) allow(Lumberjack::Logger).to receive(:new).and_return(logger) allow(logger).to receive(:info) allow(logger).to receive(:warn) allow(logger).to receive(:error) allow(logger).to receive(:debug) allow(logger).to receive(:level=) end after { described_class.reset } describe ".logger" do before do allow(described_class.options).to receive(:device).and_return(device) end context "with no logger set yet" do let(:device) { "foo.log" } it "returns the logger instance" do expect(described_class.logger).to be(logger) end it "sets the logger device" do expect(Lumberjack::Logger).to receive(:new).with(device, described_class.logger_config) described_class.logger end end end describe ".level=" do let(:level) { Logger::WARN } context "when logger is set up" do before { described_class.logger } it "sets the logger's level" do expect(logger).to receive(:level=).with(level) described_class.level = level end it "sets the logger's config level" do expect(described_class.logger_config).to receive(:level=).with(level) described_class.level = level end end context "when logger is not set up yet" do before { described_class.reset } it "sets the logger's config level" do expect(described_class.logger_config).to receive(:level=).with(level) described_class.level = level end it "does not autocreate the logger" do expect(logger).to_not receive(:level=) described_class.level = level end end end describe ".options=" do it "sets the logger options" do described_class.options = { hi: :ho } expect(described_class.options[:hi]).to eq :ho end end shared_examples_for "a logger method" do it "resets the line with the :reset option" do expect(described_class).to receive :reset_line described_class.send(ui_method, input, reset: true) end it "logs the message with the given severity" do expect(logger).to receive(severity).with(output) described_class.send(ui_method, input) end context "with the :only option" do before { described_class.options = { only: /A/ } } it "allows logging matching messages" do expect(logger).to receive(severity).with(output) described_class.send(ui_method, input, plugin: "A") end it "prevents logging other messages" do expect(logger).to_not receive(severity) described_class.send(ui_method, input, plugin: "B") end end context "with the :except option" do before { described_class.options = { except: /A/ } } it "prevents logging matching messages" do expect(logger).to_not receive(severity) described_class.send(ui_method, input, plugin: "A") end it "allows logging other messages" do expect(logger).to receive(severity).with(output) described_class.send(ui_method, input, plugin: "B") end end end describe ".info" do it_behaves_like "a logger method" do let(:ui_method) { :info } let(:severity) { :info } let(:input) { "Info" } let(:output) { "Info" } end end describe ".warning" do it_behaves_like "a logger method" do let(:ui_method) { :warning } let(:severity) { :warn } let(:input) { "Warning" } let(:output) { "\e[0;33mWarning\e[0m" } end end describe ".error" do it_behaves_like "a logger method" do let(:ui_method) { :error } let(:severity) { :error } let(:input) { "Error" } let(:output) { "\e[0;31mError\e[0m" } end end describe ".deprecation" do before do allow(ENV).to receive(:[]).with("GUARD_GEM_SILENCE_DEPRECATIONS") .and_return(value) end context "with GUARD_GEM_SILENCE_DEPRECATIONS set to 1" do let(:value) { "1" } it "silences deprecations" do expect(described_class.logger).to_not receive(:warn) described_class.deprecation "Deprecator message" end end context "with GUARD_GEM_SILENCE_DEPRECATIONS unset" do let(:value) { nil } it_behaves_like "a logger method" do let(:ui_method) { :deprecation } let(:severity) { :warn } let(:input) { "Deprecated" } let(:output) do /^\e\[0;33mDeprecated\nDeprecation backtrace: .*\e\[0m$/m end end end end describe ".debug" do it_behaves_like "a logger method" do let(:ui_method) { :debug } let(:severity) { :debug } let(:input) { "Debug" } let(:output) { "\e[0;33mDebug\e[0m" } end end describe ".clear" do context "with UI set up and ready" do before do allow(session).to receive(:clear?).and_return(false) described_class.reset_and_clear end context "when clear option is disabled" do it "does not clear the output" do expect(terminal).to_not receive(:clear) described_class.clear end end context "with no engine" do before do allow(described_class).to receive(:engine).and_return(nil) end context "when the screen is marked as needing clearing" do it "clears the output" do expect(terminal).to_not receive(:clear) described_class.clear end end end context "when clear option is enabled" do before do allow(session).to receive(:clear?).and_return(true) allow(described_class).to receive(:engine).and_return(engine) end context "when the screen is marked as needing clearing" do before { described_class.clearable! } it "clears the output" do expect(terminal).to receive(:clear) described_class.clear end it "clears the output only once" do expect(terminal).to receive(:clear).once described_class.clear described_class.clear end context "when the command fails" do before do allow(terminal).to receive(:clear) .and_raise(Errno::ENOENT, "failed to run command") end it "shows a warning" do expect(logger).to receive(:warn) do |arg| expect(arg).to match(/failed to run command/) end described_class.clear end end end context "when the screen has just been cleared" do before { described_class.clear } it "does not clear" do expect(terminal).to_not receive(:clear) described_class.clear end context "when forced" do let(:opts) { { force: true } } it "clears the outputs if forced" do expect(terminal).to receive(:clear) described_class.clear(opts) end end end end end end describe ".action_with_scopes" do context "with a plugins scope" do it "shows the plugin scoped action" do expect(described_class).to receive(:info).with("Reload Rspec, Jasmine") described_class.action_with_scopes("Reload", %w[Rspec Jasmine]) end end context "with a groups scope" do it "shows the group scoped action" do expect(described_class).to receive(:info).with("Reload Frontend") described_class.action_with_scopes("Reload", ["Frontend"]) end end context "without a scope" do context "with a global plugin scope" do it "shows the global plugin scoped action" do expect(described_class).to receive(:info).with("Reload Rspec, Jasmine") described_class.action_with_scopes("Reload", %w[Rspec Jasmine]) end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/cli_spec.rb
spec/lib/guard/cli_spec.rb
# frozen_string_literal: true require "guard/cli" RSpec.describe Guard::CLI do include_context "Guard options" let(:write_environment) { instance_double("Guard::Cli::Environments::Write") } let(:read_only_environment) do instance_double("Guard::Cli::Environments::ReadOnly") end let(:dsl_describer) { instance_double("Guard::DslDescriber") } before do allow(subject).to receive(:options).and_return(options) allow(Guard::DslDescriber).to receive(:new).and_return(dsl_describer) allow(Guard::Cli::Environments::ReadOnly).to receive(:new).with(options).and_return(read_only_environment) allow(Guard::Cli::Environments::Write).to receive(:new).with(options).and_return(write_environment) end describe "#start" do before do allow(read_only_environment).to receive(:start).and_return(0) end it "delegates to Guard::Environment.start" do expect(read_only_environment).to receive(:start).and_return(0) begin subject.start rescue SystemExit end end it "exits with given exit code" do allow(read_only_environment).to receive(:start).and_return(4) expect { subject.start }.to raise_error(SystemExit) do |exception| expect(exception.status).to eq(4) exception end end it "passes options" do expect(Guard::Cli::Environments::ReadOnly) .to receive(:new) .with(options) .and_return(read_only_environment) begin subject.start rescue SystemExit end end end describe "#list" do before do allow(read_only_environment).to receive(:evaluate).and_return(read_only_environment) allow(dsl_describer).to receive(:list) subject.list end it "calls the evaluation" do expect(read_only_environment).to have_received(:evaluate) end it "outputs the Guard plugins list" do expect(dsl_describer).to have_received(:list) end end describe "#notifiers" do before do allow(read_only_environment).to receive(:evaluate).and_return(read_only_environment) allow(dsl_describer).to receive(:notifiers) subject.notifiers end it "calls the evaluation" do expect(read_only_environment).to have_received(:evaluate) end it "outputs the notifiers list" do expect(dsl_describer).to have_received(:notifiers) end end describe "#version" do it "shows the current version" do expect(STDOUT).to receive(:puts).with(/#{::Guard::VERSION}/) subject.version end end describe "#init" do before do allow(Guard::Cli::Environments::Write).to receive(:new) .and_return(write_environment) allow(write_environment).to receive(:initialize_guardfile).and_return(0) end it "exits with given exit code" do allow(write_environment).to receive(:initialize_guardfile).and_return(4) expect { subject.init }.to raise_error(SystemExit) do |exception| expect(exception.status).to eq(4) end end it "passes options" do expect(Guard::Cli::Environments::Write).to receive(:new).with(options) .and_return(write_environment) begin subject.init rescue SystemExit end end it "passes plugin names" do plugins = [double("plugin1"), double("plugin2")] expect(write_environment).to receive(:initialize_guardfile).with(plugins) begin subject.init(*plugins) rescue SystemExit end end end describe "#show" do before do allow(read_only_environment).to receive(:evaluate).and_return(read_only_environment) allow(dsl_describer).to receive(:show) subject.show end it "calls the evaluation" do expect(read_only_environment).to have_received(:evaluate) end it "outputs the Guard::DslDescriber.list result" do expect(dsl_describer).to have_received(:show) end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/dsl_describer_spec.rb
spec/lib/guard/dsl_describer_spec.rb
# frozen_string_literal: true require "guard/dsl_describer" require "guard/guardfile/result" RSpec.describe Guard::DslDescriber, :stub_ui do let(:guardfile_result) { Guard::Guardfile::Result.new } let(:interactor) { instance_double(Guard::Interactor) } let(:env) { double("ENV") } subject { described_class.new(guardfile_result) } before do guardfile_result.plugins << [:another, {}] << [:test, {}] allow(env).to receive(:[]).with("GUARD_NOTIFY_PID") allow(env).to receive(:[]).with("GUARD_NOTIFY") allow(env).to receive(:[]).with("GUARD_NOTIFIERS") allow(env).to receive(:[]=).with("GUARD_NOTIFIERS", anything) allow(Guard::Notifier).to receive(:turn_on) @output = +"" # Strip escape sequences allow(STDOUT).to receive(:tty?).and_return(false) # Capture formatador output Thread.current[:formatador] = Formatador.new allow(Thread.current[:formatador]).to receive(:print) do |msg| @output << msg end end describe "#list" do let(:result) do <<-OUTPUT +---------+-----------+ | Plugin | Guardfile | +---------+-----------+ | Another | ✔ | | Even | ✘ | | More | ✘ | | Test | ✔ | +---------+-----------+ OUTPUT end before do allow(Guard::PluginUtil).to receive(:plugin_names) do %w[test another even more] end end it "lists the available Guards declared as strings or symbols" do subject.list expect(@output).to eq result end end describe ".show" do let(:result) do <<-OUTPUT +---------+---------+--------+-------+ | Group | Plugin | Option | Value | +---------+---------+--------+-------+ | default | test | a | :b | | | | c | :d | +---------+---------+--------+-------+ | a | test | x | 1 | | | | y | 2 | +---------+---------+--------+-------+ | b | another | | | +---------+---------+--------+-------+ OUTPUT end before do guardfile_result.groups.merge!(default: {}, a: {}, b: {}) guardfile_result.plugins << [:test, { a: :b, c: :d, group: :default }] guardfile_result.plugins << [:test, { x: 1, y: 2, group: :a }] guardfile_result.plugins << [:another, { group: :b }] end it "shows the Guards and their options" do subject.show expect(@output).to eq result end end describe ".notifiers" do let(:result) do <<-OUTPUT +----------------+-----------+------+--------+-------+ | Name | Available | Used | Option | Value | +----------------+-----------+------+--------+-------+ | gntp | ✔ | ✔ | sticky | true | +----------------+-----------+------+--------+-------+ | terminal_title | ✘ | ✘ | | | +----------------+-----------+------+--------+-------+ OUTPUT end before do allow(Guard::Notifier).to receive(:supported).and_return( gntp: ::Notiffany::Notifier::GNTP, terminal_title: ::Notiffany::Notifier::TerminalTitle ) allow(Guard::Notifier).to receive(:connect).once allow(Guard::Notifier).to receive(:detected) .and_return([{ name: :gntp, options: { sticky: true } }]) allow(Guard::Notifier).to receive(:disconnect).once end it "properly connects and disconnects" do expect(Guard::Notifier).to receive(:connect).once.ordered expect(::Guard::Notifier).to receive(:detected).once.ordered.and_return [ { name: :gntp, options: { sticky: true } } ] expect(Guard::Notifier).to receive(:disconnect).once.ordered subject.notifiers end it "shows the notifiers and their options" do subject.notifiers expect(@output).to eq result end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/plugin_spec.rb
spec/lib/guard/plugin_spec.rb
# frozen_string_literal: true require "guard/plugin" RSpec.describe Guard::Plugin, :stub_ui do include_context "with engine" subject { described_class.new(engine: engine) } describe "#initialize" do it "assigns the defined watchers" do watchers = [double("foo")] expect(described_class.new(watchers: watchers).watchers).to eq(watchers) end it "assigns the defined options" do options = { a: 1, b: 2 } expect(described_class.new(options).options).to eq(options) end context "with a group in the options" do it "assigns the given group" do group = described_class.new(group: engine.groups.find(:default)).group expect(group).to match a_kind_of(Guard::Group) expect(group.name).to eq(:default) end end context "without a group in the options" do it "assigns a default group" do group = described_class.new.group expect(group).to be_nil end end context "with a callback" do it "adds the callback" do block1 = instance_double(Proc) block2 = instance_double(Proc) callbacks = [ { events: [:start_begin], listener: block1 }, { events: [:start_end], listener: block2 } ] plugin = described_class.new(engine: engine, callbacks: callbacks) expect(Guard::Plugin.callbacks[[plugin, :start_begin]]).to eq([block1]) expect(Guard::Plugin.callbacks[[plugin, :start_end]]).to eq([block2]) end end end context "with a specific plugin" do describe "class methods" do subject { Guard::Dummy } describe ".non_namespaced_classname" do it "remove the Guard:: namespace" do expect(subject.non_namespaced_classname).to eq "Dummy" end end describe ".non_namespaced_name" do it "remove the Guard:: namespace and downcase" do expect(subject.non_namespaced_name).to eq "dummy" end end describe ".template" do before do allow(File).to receive(:read) end it "reads the default template" do expect(File).to receive(:read) .with("/guard-dummy/lib/guard/dummy/templates/Guardfile") { true } subject.template("/guard-dummy") end end end describe "instance methods" do subject { Guard::Dummy.new(engine: engine) } describe "#name" do it "outputs the short plugin name" do expect(subject.name).to eq "dummy" end end describe "#title" do it "outputs the plugin title" do expect(subject.title).to eq "Dummy" end end describe "#to_s" do it "output the short plugin name" do expect(subject.to_s) .to match(/#<Guard::Dummy:\d+ @name=dummy .*>/) end end end end let(:listener) { instance_double(Proc, call: nil) } describe ".add_callback" do let(:foo) { double("foo plugin") } it "can add a run_on_modifications callback" do described_class.add_callback( listener, foo, :run_on_modifications_begin ) result = described_class.callbacks[[foo, :run_on_modifications_begin]] expect(result).to include(listener) end it "can add multiple callbacks" do described_class.add_callback(listener, foo, %i[event1 event2]) result = described_class.callbacks[[foo, :event1]] expect(result).to include(listener) result = described_class.callbacks[[foo, :event2]] expect(result).to include(listener) end end describe ".notify" do let(:foo) { double("foo plugin") } let(:bar) { double("bar plugin") } before do described_class.add_callback(listener, foo, :start_begin) end it "sends :call to the given Guard class's start_begin callback" do expect(listener).to receive(:call).with(foo, :start_begin, "args") described_class.notify(foo, :start_begin, "args") end it "sends :call to the given Guard class's start_begin callback" do expect(listener).to receive(:call).with(foo, :start_begin, "args") described_class.notify(foo, :start_begin, "args") end it "runs only the given callbacks" do listener2 = double("listener2") described_class.add_callback(listener2, foo, :start_end) expect(listener2).to_not receive(:call).with(foo, :start_end) described_class.notify(foo, :start_begin) end it "runs callbacks only for the guard given" do described_class.add_callback(listener, bar, :start_begin) expect(listener).to_not receive(:call).with(bar, :start_begin) described_class.notify(foo, :start_begin) end end describe "#hook" do subject { Guard::Dummy.new(engine: engine) } before do described_class.add_callback(listener, subject, :start_begin) end it "notifies the hooks" do module Guard class Dummy < Guard::Plugin def run_all hook :begin hook :end end end end expect(described_class).to receive(:notify).with(subject, :run_all_begin) expect(described_class).to receive(:notify).with(subject, :run_all_end) subject.run_all end it "passes the hooks name" do module Guard class Dummy < Guard::Plugin def start hook "my_hook" end end end expect(described_class).to receive(:notify).with(subject, :my_hook) subject.start end it "accepts extra arguments" do module Guard class Dummy < Guard::Plugin def stop hook :begin, "args" hook "special_sauce", "first_arg", "second_arg" end end end expect(described_class).to receive(:notify) .with(subject, :stop_begin, "args") expect(described_class).to receive(:notify) .with(subject, :special_sauce, "first_arg", "second_arg") subject.stop end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/bin_spec.rb
spec/lib/guard/bin_spec.rb
# frozen_string_literal: true path = File.expand_path("../../../bin/guard", __dir__) load path RSpec.describe GuardReloader do let(:config) { instance_double(described_class::Config) } subject { described_class.new(config) } let(:guard_core_path) { "/home/me/.rvm/gems/ruby-2.2.2/bin/_guard-core" } before do allow(described_class::Config).to receive(:new).and_return(config) allow(config).to receive(:current_bundler_gemfile) .and_return(bundle_gemfile_env) allow(config).to receive(:using_bundler?).and_return(bundle_gemfile_env) allow(config).to receive(:guard_core_path).and_return(guard_core_path) allow(config).to receive(:program_arguments).and_return(%w[foo bar baz]) allow(config).to receive(:using_rubygems?).and_return(rubygems_deps_env) allow(config).to receive(:program_path).and_return(program_path) end let(:program_path) { Pathname("/home/me/.rvm/gems/ruby-2.2.2/bin/guard") } let(:rubygems_deps_env) { nil } # or any gemfile path context "when running with bundler" do let(:bundle_gemfile_env) { "./Gemfile" } it "sets up bundler" do expect(config).to receive(:setup_bundler) subject.setup end end context "when not running with bundler" do let(:bundle_gemfile_env) { nil } context "when running with rubygems_gemdeps" do let(:rubygems_deps_env) { "-" } # or any gemfile path it "sets up rubygems" do expect(config).to receive(:setup_rubygems_for_deps) subject.setup end end context "when not running with rubygems_gemdeps" do let(:rubygems_deps_env) { nil } context "when running as binstub" do let(:program_path) { Pathname("/my/project/bin/guard") } context "when the relative Gemfile exists" do before do allow(config).to receive(:exist?) .with(Pathname("/my/project/Gemfile")).and_return(true) allow(config).to receive(:setup_bundler) allow(config).to receive(:setup_bundler_env) end it "sets up bundler" do expect(config).to receive(:setup_bundler) subject.setup end it "sets the Gemfile" do expect(config).to receive(:setup_bundler_env) .with("/my/project/Gemfile") subject.setup end end context "when the relative Gemfile does not exist" do before do allow(config).to receive(:exist?) .with(Pathname("/my/project/Gemfile")).and_return(false) allow(config).to receive(:exist?).with(Pathname("Gemfile")) .and_return(false) end it "does not setup bundler" do subject.setup end it "does not setup rubygems" do subject.setup end it "shows no warning" do expect(STDERR).to_not receive(:puts) subject.setup end end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/runner_spec.rb
spec/lib/guard/runner_spec.rb
# frozen_string_literal: true require "guard/runner" RSpec.describe Guard::Runner, :stub_ui do include_context "with engine" let(:frontend_group) { engine.groups.add(:frontend) } let(:backend_group) { engine.groups.add(:backend) } let!(:dummy_plugin) { plugins.add("dummy", group: frontend_group, watchers: [Guard::Watcher.new("hello")]) } let!(:doe_plugin) { plugins.add("doe", group: frontend_group) } let!(:foobar_plugin) { plugins.add("foobar", group: backend_group) } let!(:foobaz_plugin) { plugins.add("foobaz", group: backend_group) } subject { described_class.new(engine.session) } describe "#run" do it "executes supervised task on all registered plugins implementing it" do [dummy_plugin, doe_plugin, foobar_plugin, foobaz_plugin].each do |plugin| expect(plugin).to receive(:title) end subject.run(:title) end it "marks an action as unit of work" do expect(Lumberjack).to receive(:unit_of_work) subject.run(:my_task) end context "with interrupted task" do before do allow(dummy_plugin).to receive(:title).and_raise(Interrupt) end it "catches the thrown symbol" do expect { subject.run(:title) }.to_not throw_symbol(:task_has_failed) end end [:dummy, [:dummy]].each do |entries| context "with entries: #{entries}" do it "executes the supervised task on the specified plugin only" do expect(dummy_plugin).to receive(:title) [doe_plugin, foobar_plugin, foobaz_plugin].each do |plugin| expect(plugin).to_not receive(:title) end subject.run(:title, entries) end end end context "with no scope" do it "executes the supervised task using current scope" do [dummy_plugin, doe_plugin, foobar_plugin, foobaz_plugin].each do |plugin| expect(plugin).to receive(:title) end subject.run(:title) end end end describe "#run_on_changes" do let(:matching_files) { ["hello"] } shared_examples "cleared terminal" do it "always calls UI.clearable!" do expect(Guard::UI).to receive(:clearable!) subject.run_on_changes(*changes) end context "when clearable" do it "clear UI" do expect(Guard::UI).to receive(:clear).exactly(4).times subject.run_on_changes(*changes) end end end context "with no changes" do let(:changes) { [[], [], []] } it_behaves_like "cleared terminal" it "does not run any task" do %w[ run_on_modifications run_on_change run_on_additions run_on_removals run_on_deletion ].each do |task| expect(dummy_plugin).to_not receive(task.to_sym) end subject.run_on_changes(*changes) end end context "with non-matching modified paths" do let(:changes) { [%w[file.txt image.png], [], []] } it "does not call run anything" do expect(dummy_plugin).to_not receive(:run_on_modifications) subject.run_on_changes(*changes) end end context "with matching modified paths" do let(:changes) { [matching_files, [], []] } it "executes the :run_first_task_found task" do expect(dummy_plugin).to receive(:run_on_modifications).with(matching_files) {} subject.run_on_changes(*changes) end end context "with non-matching added paths" do let(:changes) { [[], %w[file.txt image.png], []] } it "does not call run anything" do expect(dummy_plugin).to_not receive(:run_on_additions) subject.run_on_changes(*changes) end end context "with matching added paths" do let(:changes) { [[], matching_files, []] } it "executes the :run_on_additions task" do expect(dummy_plugin).to receive(:run_on_additions).with(matching_files) {} subject.run_on_changes(*changes) end end context "with non-matching removed paths" do let(:removed) { %w[file.txt image.png] } let(:changes) { [[], [], %w[file.txt image.png]] } it "does not call tasks" do expect(dummy_plugin).to_not receive(:run_on_removals) subject.run_on_changes(*changes) end end context "with matching removed paths" do let(:changes) { [[], [], matching_files] } it "executes the :run_on_removals task" do expect(dummy_plugin).to receive(:run_on_removals).with(matching_files) {} subject.run_on_changes(*changes) end end end describe "#_supervise" do it "executes the task on the passed plugin" do expect(dummy_plugin).to receive(:title) subject.__send__(:_supervise, dummy_plugin, :title) end context "with a task that succeeds" do context "without any arguments" do it "does not remove the plugin" do expect(plugins).to_not receive(:remove) subject.__send__(:_supervise, dummy_plugin, :title) end it "returns the result of the task" do result = subject.__send__(:_supervise, dummy_plugin, :title) expect(result).to be_truthy end it "calls :begin and :end hooks and passes the result of the supervised method to the :end hook" do expect(dummy_plugin).to receive(:hook) .with("title_begin") expect(dummy_plugin).to receive(:hook) .with("title_end", "Dummy") subject.__send__(:_supervise, dummy_plugin, :title) end end context "with arguments" do it "does not remove the Guard" do expect(plugins).to_not receive(:remove) subject.__send__( :_supervise, dummy_plugin, :run_on_changes, "given_path" ) end it "returns the result of the task" do result = subject.__send__( :_supervise, dummy_plugin, :run_on_changes, "given_path" ) expect(result).to eq "I'm a success" end end end context "with a task that throws :task_has_failed" do context "in a group" do context "with halt_on_fail: true" do before { frontend_group.options[:halt_on_fail] = true } it "throws :task_has_failed" do expect do subject.__send__(:_supervise, dummy_plugin, :throwing) end.to throw_symbol(:task_has_failed) end end context "with halt_on_fail: false" do before { frontend_group.options[:halt_on_fail] = false } it "catches :task_has_failed" do expect do subject.__send__(:_supervise, dummy_plugin, :throwing) end.to_not throw_symbol(:task_has_failed) end end end end context "with a task that raises an exception" do it "removes the plugin" do expect(plugins).to receive(:remove).with(dummy_plugin) {} subject.__send__(:_supervise, dummy_plugin, :failing) end it "display an error to the user" do expect(::Guard::UI).to receive :error expect(::Guard::UI).to receive :info subject.__send__(:_supervise, dummy_plugin, :failing) end it "returns the exception" do failing_result = subject.__send__(:_supervise, dummy_plugin, :failing) expect(failing_result).to be_kind_of(Exception) expect(failing_result.message).to eq "I break your system" end it "calls the default begin hook but not the default end hook" do expect(dummy_plugin).to receive(:hook).with("failing_begin") expect(dummy_plugin).to_not receive(:hook).with("failing_end") subject.__send__(:_supervise, dummy_plugin, :failing) end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/config_spec.rb
spec/lib/guard/config_spec.rb
# frozen_string_literal: true require "guard/config" RSpec.describe Guard::Config do it { is_expected.to respond_to(:strict?) } it { is_expected.to respond_to(:silence_deprecations?) } describe ".strict?" do before do allow(subject).to receive(:strict?).and_return(result) end context "when GUARD_STRICT is set to a 'true' value" do let(:result) { true } it { is_expected.to be_strict } end context "when GUARD_STRICT is set to a 'false' value" do let(:result) { false } it { is_expected.to_not be_strict } end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/engine_spec.rb
spec/lib/guard/engine_spec.rb
# frozen_string_literal: true require "guard/engine" require "guard/plugin" require "guard/jobs/pry_wrapper" require "guard/jobs/sleep" RSpec.describe Guard::Engine, :stub_ui do include_context "with engine" let(:traps) { Guard::Internals::Traps } describe "#session" do it "passes options to #session" do expect(Guard::Internals::Session).to receive(:new).with(options).and_call_original engine.session end end describe "#start" do subject(:start_engine) { engine.start } before do allow(engine.__send__(:_runner)).to receive(:run).with(:start) allow(engine.__send__(:_runner)).to receive(:run).with(:stop) end after { engine.stop } it "connects to the notifier" do expect(Guard::Notifier).to receive(:connect).with(engine.session.notify_options) start_engine end describe "listener initialization" do let(:options) { base_options.merge(watchdirs: "/foo", latency: 2, wait_for_delay: 1) } it "initializes the listener" do expect(Listen).to receive(:to) .with("/foo", latency: 2, wait_for_delay: 1).and_return(listener) start_engine end end describe "signals trapping" do before do allow(traps).to receive(:handle) end it "sets up USR1 trap for pausing" do expect(traps).to receive(:handle).with("USR1") { |_, &b| b.call } expect(engine).to receive(:async_queue_add) .with(%i[pause paused]) start_engine end it "sets up USR2 trap for unpausing" do expect(traps).to receive(:handle).with("USR2") { |_, &b| b.call } expect(engine).to receive(:async_queue_add) .with(%i[pause unpaused]) start_engine end it "sets up INT trap for cancelling or quitting interactor" do expect(traps).to receive(:handle).with("INT") { |_, &b| b.call } expect(interactor).to receive(:handle_interrupt) start_engine end end describe "interactor initialization" do it "initializes the interactor" do expect(Guard::Interactor).to receive(:new).with(engine, false) start_engine end end it "evaluates the Guardfile" do expect(engine.evaluator).to receive(:evaluate).and_call_original start_engine end describe "listener" do subject { listener } before { start_engine } context "with ignores 'ignore(/foo/)' and 'ignore!(/bar/)'" do let(:inline_guardfile) { "ignore(/foo/); ignore!(/bar/); guard :dummy" } it { is_expected.to have_received(:ignore).with([/foo/]) } it { is_expected.to have_received(:ignore!).with([/bar/]) } end context "without ignores" do it { is_expected.to_not have_received(:ignore) } it { is_expected.to_not have_received(:ignore!) } end end context "no plugins given" do let(:options) { { inline: "" } } it "displays an error message when no guard are defined in Guardfile" do expect(Guard::UI).to receive(:error) .with("No Guard plugins found in Guardfile, please add at least one.") start_engine end end describe "#interactor" do context "with interactions enabled" do let(:type) { :pry_wrapper } let(:options) { { inline: "guard :dummy", no_interactions: false } } it "initializes a new interactor" do expect(Guard::Interactor).to receive(:new).with(engine, true) start_engine end end context "with interactions disabled" do let(:type) { :sleep } let(:options) { { inline: "guard :dummy", no_interactions: true } } it "does not initialize a new interactor" do expect(Guard::Interactor).to receive(:new).with(engine, false) start_engine end end end describe "UI" do subject { Guard::UI } context "when clearing is configured" do before { start_engine } it { is_expected.to have_received(:reset_and_clear) } end end it "displays an info message" do expect(Guard::UI).to receive(:debug) .with("Guard starts all plugins") expect(Guard::UI).to receive(:info) .with("Using inline Guardfile.") expect(Guard::UI).to receive(:info) .with("Guard is now watching at '#{Dir.pwd}'") start_engine end it "tell the runner to run the :start task" do expect(engine.__send__(:_runner)).to receive(:run).with(:start) start_engine end it "start the listener" do expect(listener).to receive(:start) start_engine end context "when finished" do it "stops everything" do expect(engine.__send__(:_runner)).to receive(:run).with(:start) expect(interactor).to receive(:foreground).and_return(:exit) # From stop() expect(interactor).to receive(:background) expect(listener).to receive(:stop) expect(engine.__send__(:_runner)).to receive(:run).with(:stop) expect(Guard::UI).to receive(:info).with("Bye bye...", reset: true) start_engine end end context "when listener.start raises an error" do it "calls #stop" do allow(listener).to receive(:start).and_raise(RuntimeError) # From stop() expect(interactor).to receive(:background) expect(listener).to receive(:stop) expect(engine.__send__(:_runner)).to receive(:run).with(:stop) expect(Guard::UI).to receive(:info).with("Bye bye...", reset: true) expect { start_engine }.to raise_error(RuntimeError) end end context "when setup raises an error" do it "calls #stop" do # Reproduce a case where an error is raised during Guardfile evaluation # before the listener and interactor are instantiated. expect(engine).to receive(:setup).and_raise(RuntimeError) # From stop() expect(engine.__send__(:_runner)).to receive(:run).with(:stop) expect(Guard::UI).to receive(:info).with("Bye bye...", reset: true) expect { start_engine }.to raise_error(RuntimeError) end end end describe "#stop" do it "connects to the notifier" do expect(listener).to receive(:stop) expect(interactor).to receive(:background) expect(Guard::UI).to receive(:debug).with("Guard stops all plugins") expect(engine.__send__(:_runner)).to receive(:run).with(:stop) expect(Guard::Notifier).to receive(:disconnect) expect(Guard::UI).to receive(:info).with("Bye bye...", reset: true) engine.stop end it "turns off the interactor" do expect(interactor).to receive(:background) engine.stop end it "turns the notifier off" do expect(Guard::Notifier).to receive(:disconnect) engine.stop end it "tell the runner to run the :stop task" do expect(engine.__send__(:_runner)).to receive(:run).with(:stop) engine.stop end it "stops the listener" do expect(listener).to receive(:stop) engine.stop end end describe "#reload" do before do allow(engine.__send__(:_runner)).to receive(:run) engine.setup end it "clears the screen and prints information message" do expect(Guard::UI).to receive(:clear) expect(Guard::UI).to receive(:action_with_scopes).with("Reload", engine.session.scope_titles({})) engine.reload end context "with an empty scope" do it "runs all" do expect(engine.__send__(:_runner)).to receive(:run).with(:reload, []) engine.reload end end context "with a given scope" do it "runs all with the scope" do expect(engine.__send__(:_runner)).to receive(:run).with(:reload, [:default]) engine.reload(:default) end end context "with multiple given scope" do it "runs all with the scope" do expect(engine.__send__(:_runner)).to receive(:run).with(:reload, %i[default frontend]) engine.reload(:default, :frontend) end end context "with multiple given scope as array" do it "runs all with the scope" do expect(engine.__send__(:_runner)).to receive(:run).with(:reload, %i[default frontend]) engine.reload(%i[default frontend]) end end end describe "#run_all" do before do engine.setup end it "clears the screen and prints information message" do expect(Guard::UI).to receive(:clear) expect(Guard::UI).to receive(:action_with_scopes).with("Run", engine.session.scope_titles({})) engine.run_all end context "with an empty scope" do it "runs all" do expect(engine.__send__(:_runner)).to receive(:run).with(:run_all, []) engine.run_all end end context "with a given scope" do it "runs all with the scope" do expect(engine.__send__(:_runner)).to receive(:run).with(:run_all, [:default]) engine.run_all(:default) end end context "with multiple given scope" do it "runs all with the scope" do expect(engine.__send__(:_runner)).to receive(:run).with(:run_all, %i[default frontend]) engine.run_all(:default, :frontend) end end context "with multiple given scope as array" do it "runs all with the scope" do expect(engine.__send__(:_runner)).to receive(:run).with(:run_all, %i[default frontend]) engine.run_all(%i[default frontend]) end end end describe "#pause" do context "when unpaused" do before do allow(engine).to receive(:_listener).and_return(listener) allow(listener).to receive(:paused?) { false } end [:toggle, nil, :paused].each do |mode| context "with #{mode.inspect}" do before do allow(listener).to receive(:pause) end it "pauses" do expect(listener).to receive(:pause) engine.pause(mode) end it "shows a message" do expected = /File event handling has been paused/ expect(Guard::UI).to receive(:info).with(expected) engine.pause(mode) end end end context "with :unpaused" do it "does nothing" do expect(listener).to_not receive(:start) expect(listener).to_not receive(:pause) engine.pause(:unpaused) end end context "with invalid parameter" do it "raises an ArgumentError" do expect { engine.pause(:invalid) } .to raise_error(ArgumentError, "invalid mode: :invalid") end end end context "when already paused" do before do allow(engine).to receive(:_listener).and_return(listener) allow(listener).to receive(:paused?) { true } end [:toggle, nil, :unpaused].each do |mode| context "with #{mode.inspect}" do before do allow(listener).to receive(:start) end it "unpauses" do expect(listener).to receive(:start) engine.pause(mode) end it "shows a message" do expected = /File event handling has been resumed/ expect(Guard::UI).to receive(:info).with(expected) engine.pause(mode) end end end context "with :paused" do it "does nothing" do expect(listener).to_not receive(:start) expect(listener).to_not receive(:pause) engine.pause(:paused) end end context "with invalid parameter" do it "raises an ArgumentError" do expect { engine.pause(:invalid) } .to raise_error(ArgumentError, "invalid mode: :invalid") end end end end describe "#show" do let(:dsl_describer) { instance_double("Guard::DslDescriber") } before do allow(Guard::DslDescriber).to receive(:new).with(engine) .and_return(dsl_describer) end it "shows list of plugins" do expect(dsl_describer).to receive(:show) engine.show end end describe "._relative_pathname" do subject { engine.__send__(:_relative_pathname, raw_path) } let(:pwd) { Pathname("/project") } before { allow(Pathname).to receive(:pwd).and_return(pwd) } context "with file in project directory" do let(:raw_path) { "/project/foo" } it { is_expected.to eq(Pathname("foo")) } end context "with file within project" do let(:raw_path) { "/project/spec/models/foo_spec.rb" } it { is_expected.to eq(Pathname("spec/models/foo_spec.rb")) } end context "with file in parent directory" do let(:raw_path) { "/foo" } it { is_expected.to eq(Pathname("../foo")) } end context "with file on another drive (e.g. Windows)" do let(:raw_path) { "d:/project/foo" } let(:pathname) { instance_double(Pathname) } before do allow_any_instance_of(Pathname).to receive(:relative_path_from) .with(pwd).and_raise(ArgumentError) end it { is_expected.to eq(Pathname.new("d:/project/foo")) } end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/options_spec.rb
spec/lib/guard/options_spec.rb
# frozen_string_literal: true require "guard/options" RSpec.describe Guard::Options do describe ".initialize" do it "handles nil options" do expect { described_class.new(nil) }.to_not raise_error end it "has indifferent access" do options = described_class.new({ foo: "bar" }, "foo2" => "baz") expect(options[:foo]).to eq "bar" expect(options["foo"]).to eq "bar" expect(options[:foo2]).to eq "baz" expect(options["foo2"]).to eq "baz" end it "can be passed defaults" do options = described_class.new({}, foo: "bar") expect(options[:foo]).to eq "bar" end it "merges the sensible defaults to the given options" do options = described_class.new({ plugin: ["rspec"] }, plugin: ["test"]) expect(options[:plugin]).to eq ["rspec"] end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/jobs/sleep_spec.rb
spec/lib/guard/jobs/sleep_spec.rb
# frozen_string_literal: true require "guard/jobs/sleep" RSpec.describe Guard::Jobs::Sleep, :stub_ui do include_context "with engine" subject { described_class.new(engine) } describe "#foreground" do it "sleeps" do status = "unknown" Thread.new do sleep 0.1 status = Thread.main.status subject.background end subject.foreground expect(status).to eq("sleep") end it "returns :continue when put to background" do Thread.new do sleep 0.1 subject.background end expect(subject.foreground).to eq(:continue) end end describe "#background" do it "wakes up main thread" do status = "unknown" Thread.new do sleep 0.1 # give enough time for foreground to put main thread to sleep subject.background sleep 0.1 # cause test to fail every time (without busy loop below) status = Thread.main.status Thread.main.wakeup # to get "red" in TDD without hanging end subject.foreground # go to sleep # Keep main thread busy until above thread has a chance to get status begin value = 0 Timeout.timeout(0.1) { loop { value += 1 } } rescue Timeout::Error end expect(status).to eq("run") end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/jobs/pry_wrapper_spec.rb
spec/lib/guard/jobs/pry_wrapper_spec.rb
# frozen_string_literal: true require "guard/jobs/pry_wrapper" RSpec.describe Guard::Jobs::PryWrapper, :stub_ui do include_context "with engine" let(:pry_hooks) { double("pry_hooks", add_hook: true) } let(:pry_config) do double("pry_config", "history_file=" => true, command_prefix: true, "prompt=" => true, "should_load_rc=" => true, "should_load_local_rc=" => true, hooks: pry_hooks) end let(:pry_history) { double("pry_history") } let(:pry_commands) do double("pry_commands", alias_command: true, create_command: true, command: true, block_command: true) end let(:terminal_settings) { instance_double("Guard::Jobs::TerminalSettings") } subject { described_class.new(engine) } before do allow(Pry).to receive(:config).and_return(pry_config) allow(Pry).to receive(:commands).and_return(pry_commands) allow(Guard::Commands::All).to receive(:import) allow(Guard::Commands::Change).to receive(:import) allow(Guard::Commands::Reload).to receive(:import) allow(Guard::Commands::Pause).to receive(:import) allow(Guard::Commands::Notification).to receive(:import) allow(Guard::Commands::Show).to receive(:import) allow(Guard::Commands::Scope).to receive(:import) allow(Guard::Jobs::TerminalSettings).to receive(:new) .and_return(terminal_settings) allow(terminal_settings).to receive(:configurable?).and_return(false) allow(terminal_settings).to receive(:save) allow(terminal_settings).to receive(:restore) engine.setup end describe "#_setup" do context "Guard is using Pry >= 0.13" do it "calls Pry.config.history_file=" do expect(pry_config).to receive(:history_file=) subject end end context "Guard is using Pry < 0.13" do let(:pry_config) do double("pry_config", "history" => true, command_prefix: true, "prompt=" => true, "should_load_rc=" => true, "should_load_local_rc=" => true, hooks: pry_hooks) end it "calls Pry.config.history.file=" do expect(pry_config).to receive(:history).and_return(pry_history) expect(pry_history).to receive(:file=) subject end end end describe "#foreground" do before do allow(Pry).to receive(:start) do # sleep for a long time (anything > 0.6) sleep 1 end end after do subject.background end it "waits for Pry thread to finish" do was_alive = false Thread.new do sleep 0.1 was_alive = subject.send(:thread).alive? subject.background end subject.foreground # blocks expect(was_alive).to be end it "prevents the Pry thread from being killed too quickly" do start = Time.now.to_f Thread.new do sleep 0.1 subject.background end subject.foreground # blocks killed_moment = Time.now.to_f expect(killed_moment - start).to be > 0.5 end it "return :continue when brought into background" do Thread.new do sleep 0.1 subject.background end expect(subject.foreground).to be(:continue) end end describe "#background" do before do allow(Pry).to receive(:start) do # 0.5 is enough for Pry, so we use 0.4 sleep 0.4 end end it "kills the Pry thread" do subject.foreground sleep 1 # give Pry 0.5 sec to boot subject.background sleep 0.25 # to let Pry get killed asynchronously expect(subject.send(:thread)).to be_nil end end describe "#_prompt(ending_char)" do let(:prompt) { subject.send(:_prompt, ">") } before do allow(Shellany::Sheller).to receive(:run).with("hash", "stty") { false } allow(engine).to receive(:paused?).and_return(false) allow(Pry).to receive(:view_clip).and_return("main") end context "Guard is using Pry >= 0.13" do let(:pry) { double("Pry", input_ring: []) } let(:pry_prompt) { double } it "calls Pry::Prompt.new" do expect(Pry::Prompt).to receive(:is_a?).with(Class).and_return(true) expect(Pry::Prompt).to receive(:new).with("Guard", "Guard Pry prompt", an_instance_of(Array)).and_return(pry_prompt) expect(pry_config).to receive(:prompt=).with(pry_prompt) subject end context "Guard is not paused" do it "displays 'guard'" do expect(prompt.call(double, 0, pry)) .to eq "[0] guard(main)> " end end context "Guard is paused" do before do allow(engine).to receive(:paused?).and_return(true) end it "displays 'pause'" do expect(prompt.call(double, 0, pry)) .to eq "[0] pause(main)> " end end context "with a groups scope" do before do allow(engine.session).to receive(:scope_titles).and_return(%w[Backend Frontend]) end it "displays the group scope title in the prompt" do expect(prompt.call(double, 0, pry)) .to eq "[0] Backend,Frontend guard(main)> " end end context "with a plugins scope" do before do allow(engine.session).to receive(:scope_titles).and_return(%w[RSpec Ronn]) end it "displays the group scope title in the prompt" do result = prompt.call(double, 0, pry) expect(result).to eq "[0] RSpec,Ronn guard(main)> " end end end context "Guard is using Pry < 0.13" do let(:pry) { double("Pry", input_array: []) } it "does not call Pry::Prompt.new" do expect(Pry::Prompt).to receive(:is_a?).with(Class).and_return(false) expect(pry_config).to receive(:prompt=).with(an_instance_of(Array)) subject end it "displays 'guard'" do expect(prompt.call(double, 0, pry)) .to eq "[0] guard(main)> " end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/watcher/pattern_spec.rb
spec/lib/guard/watcher/pattern_spec.rb
# frozen_string_literal: true require "guard/watcher/pattern" RSpec.describe Guard::Watcher::Pattern do describe ".create" do subject { described_class.create(pattern) } context "when a string is given" do let(:pattern) { "foo.rb" } it { is_expected.to be_a(described_class::SimplePath) } end context "when a Pathname is given" do let(:pattern) { Pathname("foo.rb") } it { is_expected.to be_a(described_class::SimplePath) } end context "when a regexp is given" do let(:pattern) { /foo\.rb/ } it { is_expected.to be_a(described_class::Matcher) } end context "when a custom matcher" do let(:pattern) { Class.new { def match; end } } it { is_expected.to be_a(described_class::Matcher) } end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/watcher/pattern/simple_path_spec.rb
spec/lib/guard/watcher/pattern/simple_path_spec.rb
# frozen_string_literal: true require "guard/watcher/pattern/simple_path" RSpec.describe Guard::Watcher::Pattern::SimplePath do subject { described_class.new(path) } describe "#match result" do context "when constructed with filename string" do let(:path) { "foo.rb" } context "when matched file is a string" do context "when filename matches" do let(:filename) { "foo.rb" } specify { expect(subject.match(filename)).to eq(["foo.rb"]) } end context "when filename does not match" do let(:filename) { "bar.rb" } specify { expect(subject.match(filename)).to be_nil } end end context "when matched file is an unclean Pathname" do context "when filename matches" do let(:filename) { Pathname("./foo.rb") } specify { expect(subject.match(filename)).to eq(["foo.rb"]) } end context "when filename does not match" do let(:filename) { Pathname("./bar.rb") } specify { expect(subject.match(filename)).to be_nil } end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/watcher/pattern/matcher_spec.rb
spec/lib/guard/watcher/pattern/matcher_spec.rb
# frozen_string_literal: true require "guard/watcher/pattern/matcher" RSpec.describe Guard::Watcher::Pattern::Matcher do subject { described_class.new(obj) } describe "#match" do let(:expected) { double("match_result") } context "when constructed with valid matcher object" do let(:obj) { double("matcher") } context "when matched against a Pathname" do before do allow(obj).to receive(:match).and_return(expected) end let(:filename) { Pathname("foo.rb") } it "returns the match result" do expect(subject.match(filename)).to be(expected) end it "passes the Pathname to the matcher" do allow(obj).to receive(:match).with(filename) subject.match(filename) end end context "when matched against a String" do before do allow(obj).to receive(:match).and_return(expected) end let(:filename) { "foo.rb" } it "returns the match result" do expect(subject.match(filename)).to be(expected) end it "passes a Pathname to the matcher" do allow(obj).to receive(:match).with(Pathname(filename)) subject.match(filename) end end end end describe "#==" do it "returns true for equal matchers" do expect(described_class.new(/spec_helper\.rb/)) .to eq(described_class.new(/spec_helper\.rb/)) end it "returns false for unequal matchers" do expect(described_class.new(/spec_helper\.rb/)) .not_to eq(described_class.new(/spec_helper\.r/)) end end describe "integration" do describe "#match result" do subject { described_class.new(obj).match(filename) } context "when constructed with valid regexp" do let(:obj) { /foo.rb$/ } context "when matched file is a string" do context "when filename matches" do let(:filename) { "foo.rb" } specify { expect(subject.to_a).to eq(["foo.rb"]) } end context "when filename does not match" do let(:filename) { "bar.rb" } specify { expect(subject).to be_nil } end end context "when matched file is an unclean Pathname" do context "when filename matches" do let(:filename) { Pathname("./foo.rb") } specify { expect(subject.to_a).to eq(["foo.rb"]) } end context "when filename does not match" do let(:filename) { Pathname("./bar.rb") } specify { expect(subject).to be_nil } end end context "when matched file contains a $" do let(:filename) { Pathname("lib$/foo.rb") } specify { expect(subject.to_a).to eq(["foo.rb"]) } end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/watcher/pattern/match_result_spec.rb
spec/lib/guard/watcher/pattern/match_result_spec.rb
# frozen_string_literal: true require "guard/watcher/pattern/match_result" RSpec.describe Guard::Watcher::Pattern::MatchResult do let(:match_result) { double("match_data") } let(:original_value) { "foo/bar.rb" } subject { described_class.new(match_result, original_value) } describe "#initialize" do context "with valid arguments" do it "does not fail" do expect { subject }.to_not raise_error end end end describe "#[]" do context "with a valid match" do let(:match_result) { double("match_data", to_a: %w[foo bar baz]) } context "when asked for the non-first item" do let(:index) { 1 } it "returns the value at given index" do expect(subject[index]).to eq("bar") end end context "when asked for the first item" do let(:index) { 0 } it "returns the full original value" do expect(subject[index]).to eq("foo/bar.rb") end end context "when asked for a name match via a symbol" do let(:index) { :foo } before do allow(match_result).to receive(:[]).with(:foo).and_return("baz") end it "returns the value by name" do expect(subject[index]).to eq("baz") end end end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/commands/show_spec.rb
spec/lib/guard/commands/show_spec.rb
# frozen_string_literal: true require "guard/commands/show" RSpec.describe Guard::Commands::Show, :stub_ui do include_context "with engine" include_context "with fake pry" before do allow(Pry::Commands).to receive(:create_command).with("show") do |&block| FakePry.instance_eval(&block) end described_class.import end it "tells Guard to output DSL description" do expect(engine).to receive(:async_queue_add).with([:show]) FakePry.process end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/commands/all_spec.rb
spec/lib/guard/commands/all_spec.rb
# frozen_string_literal: true require "guard/commands/all" RSpec.describe Guard::Commands::All, :stub_ui do include_context "with engine" include_context "with fake pry" let(:foo_group) { double } let(:bar_guard) { double } before do allow(Pry::Commands).to receive(:create_command).with("all") do |&block| FakePry.instance_eval(&block) end described_class.import end context "without scope" do let(:given_scope) { [] } let(:converted_scope) { [{ groups: [], plugins: [] }, []] } it "runs the :run_all action" do expect(engine).to receive(:async_queue_add) .with([:run_all, []]) FakePry.process end end context "with a valid Guard group scope" do let(:given_scope) { ["foo"] } let(:converted_scope) { [{ groups: [foo_group], plugins: [] }, []] } it "runs the :run_all action with the given scope" do expect(engine).to receive(:async_queue_add) .with([:run_all, ["foo"]]) FakePry.process("foo") end end context "with a valid Guard plugin scope" do let(:given_scope) { ["bar"] } let(:converted_scope) { [{ groups: [], plugins: [bar_guard] }, []] } it "runs the :run_all action with the given scope" do expect(engine).to receive(:async_queue_add) .with([:run_all, ["bar"]]) FakePry.process("bar") end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/commands/pause_spec.rb
spec/lib/guard/commands/pause_spec.rb
# frozen_string_literal: true require "guard/commands/pause" RSpec.describe Guard::Commands::Pause, :stub_ui do include_context "with engine" include_context "with fake pry" let(:output) { instance_double(Pry::Output) } before do allow(Pry::Commands).to receive(:create_command).with("pause") do |&block| FakePry.instance_eval(&block) end described_class.import end it "tells Guard to pause" do expect(engine).to receive(:async_queue_add).with([:pause]) FakePry.process end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false
guard/guard
https://github.com/guard/guard/blob/b20b7910245aee5cd4ee79fe8dc7984568afdbc4/spec/lib/guard/commands/reload_spec.rb
spec/lib/guard/commands/reload_spec.rb
# frozen_string_literal: true require "guard/commands/reload" RSpec.describe Guard::Commands::Reload, :stub_ui do include_context "with engine" include_context "with fake pry" let(:foo_group) { double } let(:bar_guard) { double } before do allow(Pry::Commands).to receive(:create_command).with("reload") do |&block| FakePry.instance_eval(&block) end described_class.import end context "without scope" do it "triggers the :reload action" do expect(engine).to receive(:async_queue_add) .with([:reload, []]) FakePry.process end end context "with a valid Guard group scope" do it "triggers the :reload action with the given scope" do expect(engine).to receive(:async_queue_add) .with([:reload, ["foo"]]) FakePry.process("foo") end end context "with a valid Guard plugin scope" do it "triggers the :reload action with the given scope" do expect(engine).to receive(:async_queue_add) .with([:reload, ["bar"]]) FakePry.process("bar") end end end
ruby
MIT
b20b7910245aee5cd4ee79fe8dc7984568afdbc4
2026-01-04T15:40:13.883835Z
false