From 8934d7cccc86006f1fe13b5d76b0c0eeadb116d0 Mon Sep 17 00:00:00 2001 From: Karel Minarik Date: Tue, 23 Oct 2012 11:26:24 +0200 Subject: [PATCH] [#446] Changed, that arbitrary objects passed in the `:as` mapping option are indexed Previously, objects other then `String` or `Proc` were silently discarded when evaluating the `:as` mapping option. With this change, you may pass whatever object you like in the `:as` mapping option: class MyModel include Some::ORM include Tire::Model::Search mapping do indexes :field, :type => 'string', :analyzer => 'keyword', :as => SomeOtherObject.whatever end end end class MyModel include Some::ORM include Tire::Model::Search mapping do indexes :field, :type => 'string', :analyzer => 'keyword', :as => [1, 2, 3] end end end This commit is a conceptual opposite of karmi/tire@0ccee42. Until #446 is decided, this change brings some consistency to the behaviour. --- lib/tire/model/search.rb | 6 ++++-- test/unit/model_search_test.rb | 24 +++++++++++++++++++++++- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/lib/tire/model/search.rb b/lib/tire/model/search.rb index b63af553..23b93bd3 100644 --- a/lib/tire/model/search.rb +++ b/lib/tire/model/search.rb @@ -154,7 +154,7 @@ def update_index # declared in the mapping are serialized. # # For properties declared with the `:as` option, the passed String or Proc - # is evaluated in the instance context. + # is evaluated in the instance context. Other objects are indexed "as is". # def to_indexed_json if instance.class.tire.mapping.empty? @@ -172,7 +172,9 @@ def to_indexed_json hash[key] = instance.instance_eval(options[:as]) when Proc hash[key] = instance.instance_eval(&options[:as]) - end + else + hash[key] = options[:as] + end if options[:as] end hash.to_json diff --git a/test/unit/model_search_test.rb b/test/unit/model_search_test.rb index 18211156..01ba0def 100644 --- a/test/unit/model_search_test.rb +++ b/test/unit/model_search_test.rb @@ -620,7 +620,7 @@ def method_missing(name, *args, &block) end - should "serialize mapped properties when mapping procs are set" do + should "evaluate :as mapping options passed as strings or procs" do class ::ModelWithMappingProcs extend ActiveModel::Naming extend ActiveModel::Callbacks @@ -656,6 +656,28 @@ def method_missing(name, *args, &block) assert_equal 3, document['three'] end + should "index :as mapping options passed as arbitrary objects" do + class ::ModelWithMappingOptionAsObject + extend ActiveModel::Naming + extend ActiveModel::Callbacks + include ActiveModel::Serialization + include Tire::Model::Search + + mapping do + indexes :one, :as => [1, 2, 3] + end + + attr_reader :attributes + + def initialize(attributes = {}); @attributes = attributes; end + end + + model = ::ModelWithMappingOptionAsObject.new + document = MultiJson.decode(model.to_indexed_json) + + assert_equal [1, 2, 3], document['one'] + end + end context "with percolation" do