Class: DataMapper::Adapters::FerretAdapter

Inherits:
AbstractAdapter
  • Object
show all
Defined in:
lib/ferret_adapter/adapter.rb

Defined Under Namespace

Classes: LocalIndex, RemoteIndex

Instance Method Summary collapse

Constructor Details

#initialize(name, options) ⇒ FerretAdapter

Returns a new instance of FerretAdapter.



4
5
6
7
8
9
10
11
# File 'lib/ferret_adapter/adapter.rb', line 4

def initialize(name, options)
  super
  @index = unless File.extname(@options[:path]) == '.sock'
    LocalIndex.new(@options)
  else
    RemoteIndex.new(@options)
  end
end

Instance Method Details

#create(resources) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/ferret_adapter/adapter.rb', line 13

def create(resources)
  resources.each do |resource|
    attributes = DataMapper::Ext::Hash.to_mash(resource.attributes(:field))

    # Since we don't inspect the models before generating the indices,
    # we'll map the resource's key to the :id column.
    attributes[:id]    ||= resource.key.first
    attributes[:_type]   = resource.model.name

    @index.add attributes
  end
end

#delete(collection) ⇒ Object



41
42
43
44
# File 'lib/ferret_adapter/adapter.rb', line 41

def delete(collection)
  @index.delete dm_query_to_ferret_query(collection.query)
  1
end

#read(query) ⇒ Object

This returns an array of Ferret docs (glorified hashes) which can be used to instantiate objects by doc and doc



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/ferret_adapter/adapter.rb', line 28

def read(query)
  fields = query.fields
  key    = query.model.key(name).first

  ferret_query = dm_query_to_ferret_query(query)

  @index.search(ferret_query, :limit => query.limit).map do |lazy_doc|
    Hash[ fields.map { |p| [ p, p.typecast(lazy_doc[p.field]) ] } ].update(
      key.field => key.typecast(lazy_doc[:id])
    )
  end
end

#search(ferret_query, limit = :all) ⇒ Object

This returns a hash of the resource constant and the ids returned for it from the search.

{ Story => ["1", "2"], Image => ["2"] }


49
50
51
52
53
54
55
56
# File 'lib/ferret_adapter/adapter.rb', line 49

def search(ferret_query, limit = :all)
  results = {}
  @index.search(ferret_query, :limit => limit).each do |doc|
    resources = results[Object.const_get(doc[:_type])] ||= []
    resources << doc[:id]
  end
  results
end