Skip to content

Commit 5486a87

Browse files
berislavbabickarmi
authored andcommitted
[MODEL] Add type and id methods to Response::Result to prevent errors with Hashie::Mash
Since Hashie::Mash explicitely [defines](https://github.com/intridea/hashie/blob/953edec/lib/hashie/mash.rb#L75-L81) `id` and `type` methods, the method_missing couldn't kick in. The `id` and `type` attributes should be referenced from the attributes hash directly, ie. from the main `_id` and `_type` properties, and not from `_source`. Closes elastic#90
1 parent b2fce1f commit 5486a87

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

elasticsearch-model/lib/elasticsearch/model/response/result.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,30 @@ def initialize(attributes={})
1717
@result = Hashie::Mash.new(attributes)
1818
end
1919

20+
# Alias `id` to `_id`
21+
#
22+
def id
23+
@result['_id']
24+
end
25+
26+
# Alias `type` to `_type`
27+
#
28+
def type
29+
@result['_type']
30+
end
31+
2032
# Delegate methods to `@result` or `@result._source`
2133
#
2234
def method_missing(name, *arguments)
2335
case
2436
when name.to_s.end_with?('?')
2537
@result.__send__(name, *arguments) || ( @result._source && @result._source.__send__(name, *arguments) )
38+
when name.to_s == "id"
39+
if @result._source && @result._source.respond_to?(name)
40+
@result._source.__send__ name, *arguments
41+
else
42+
super
43+
end
2644
when @result.respond_to?(name)
2745
@result.__send__ name, *arguments
2846
when @result._source && @result._source.respond_to?(name)

elasticsearch-model/test/integration/active_record_basic_test.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,13 @@ class ::Article < ActiveRecord::Base
7272
assert_equal [1, 2], response.records.map(&:id)
7373
end
7474

75+
should "iterate aliased id and type over results" do
76+
response = Article.search('title:test')
77+
78+
assert_equal ['1', '2'], response.results.map(&:id)
79+
assert_equal ['article', 'article'], response.results.map(&:type)
80+
end
81+
7582
should "access results from records" do
7683
response = Article.search('title:test')
7784

elasticsearch-model/test/unit/response_result_test.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,5 +73,16 @@ class Elasticsearch::Model::ResultTest < Test::Unit::TestCase
7373
result.as_json(except: 'foo')
7474
end
7575

76+
should "map the _id column to id" do
77+
result = Elasticsearch::Model::Response::Result.new foo: 'bar', _id: 42
78+
79+
assert_equal 42, result.id
80+
end
81+
82+
should "map the _type column to type" do
83+
result = Elasticsearch::Model::Response::Result.new foo: 'bar', _type: 'baz'
84+
85+
assert_equal 'baz', result.type
86+
end
7687
end
7788
end

0 commit comments

Comments
 (0)