Commit a86fc93fe1896cf4b32faa54c4e142826a72a109

Authored by Andrew Kane
1 parent f3dd9864

Added select and reselect methods on relation

Showing 2 changed files with 63 additions and 0 deletions   Show diff stats
lib/searchkick/relation.rb
... ... @@ -148,6 +148,34 @@ module Searchkick
148 148 end
149 149  
150 150 # experimental
  151 + def select(*values, &block)
  152 + if block_given?
  153 + private_execute.select(*values, &block)
  154 + else
  155 + clone.select!(*values)
  156 + end
  157 + end
  158 +
  159 + # experimental
  160 + def select!(*values)
  161 + check_loaded
  162 + (@options[:select] ||= []).concat(values)
  163 + self
  164 + end
  165 +
  166 + # experimental
  167 + def reselect(*values)
  168 + clone.reselect!(*values)
  169 + end
  170 +
  171 + # experimental
  172 + def reselect!(*values)
  173 + check_loaded
  174 + @options[:select] = values
  175 + self
  176 + end
  177 +
  178 + # experimental
151 179 def only(*keys)
152 180 Relation.new(@model, @term, **@options.slice(*keys))
153 181 end
... ...
test/select_test.rb
... ... @@ -9,6 +9,41 @@ class SelectTest < Minitest::Test
9 9 assert_equal 1, result.store_id
10 10 end
11 11  
  12 + def test_relation
  13 + store [{name: "Product A", store_id: 1}]
  14 + result = Product.search("product", load: false).select(:name, :store_id).first
  15 + assert_equal %w(id name store_id), result.keys.reject { |k| k.start_with?("_") }.sort
  16 + assert_equal "Product A", result.name
  17 + assert_equal 1, result.store_id
  18 + end
  19 +
  20 + def test_block
  21 + store [{name: "Product A", store_id: 1}, {name: "Product B", store_id: 2}]
  22 + assert_equal ["Product B"], Product.search("product", load: false).select { |v| v.store_id == 2 }.map(&:name)
  23 + end
  24 +
  25 + def test_block_arguments
  26 + store [{name: "Product A", store_id: 1}, {name: "Product B", store_id: 2}]
  27 + error = assert_raises(ArgumentError) do
  28 + Product.search("product", load: false).select(:name) { |v| v.store_id == 2 }
  29 + end
  30 + assert_equal "wrong number of arguments (given 1, expected 0)", error.message
  31 + end
  32 + def test_multiple
  33 + store [{name: "Product A", store_id: 1}]
  34 + result = Product.search("product", load: false).select(:name).select(:store_id).first
  35 + assert_equal %w(id name store_id), result.keys.reject { |k| k.start_with?("_") }.sort
  36 + assert_equal "Product A", result.name
  37 + assert_equal 1, result.store_id
  38 + end
  39 +
  40 + def test_reselect
  41 + store [{name: "Product A", store_id: 1}]
  42 + result = Product.search("product", load: false).select(:name).reselect(:store_id).first
  43 + assert_equal %w(id store_id), result.keys.reject { |k| k.start_with?("_") }.sort
  44 + assert_equal 1, result.store_id
  45 + end
  46 +
12 47 def test_array
13 48 store [{name: "Product A", user_ids: [1, 2]}]
14 49 result = Product.search("product", load: false, select: [:user_ids]).first
... ...