Skip to content

Commit

Permalink
[karmi#446] Changed, that arbitrary objects passed in the :as mappi…
Browse files Browse the repository at this point in the history
…ng 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/retire@0ccee42. Until karmi#446 is decided,
this change brings some consistency to the behaviour.
  • Loading branch information
karmi authored and NOX73 committed Oct 23, 2012
1 parent 95aef21 commit 8934d7c
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
6 changes: 4 additions & 2 deletions lib/tire/model/search.rb
Expand Up @@ -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?
Expand All @@ -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
Expand Down
24 changes: 23 additions & 1 deletion test/unit/model_search_test.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 8934d7c

Please sign in to comment.