PageRenderTime 16ms CodeModel.GetById 11ms app.highlight 4ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/ion/options.rb

http://github.com/rstacruz/ion
Ruby | 55 lines | 38 code | 11 blank | 6 comment | 1 complexity | cf549533b389ab4cd4fcaf8df921450f MD5 | raw file
 1class Ion::Options
 2  attr_reader :model
 3
 4  def initialize(model, options={})
 5    @model = model
 6    @indices = Hash.new { |h, k| h[k] = Hash.new }
 7
 8    # deserialize
 9    if options['indices']
10      options['indices'].each { |h| field h['type'], h['name'] }
11    end
12  end
13
14  def search(spec=nil, &blk)
15    Ion::Search.new(self, spec, &blk)
16  end
17
18  def key
19    @key ||= Ion.key[model.name]  #=> 'Ion:Person'
20  end
21
22  # Returns a certain index.
23  # @example
24  #   @options.index(:text, :title) #=> <#Ion::Indices::Text>
25  def index(type, name)
26    @indices[type.to_sym][name.to_sym]
27  end
28
29  # Returns all indices.
30  def indices
31    @indices.values.map(&:values).flatten
32  end
33
34  def index_types
35    indices.map(&:class).uniq
36  end
37
38  def to_hash
39    { 'indices' => indices.map { |ix| ix.to_hash } }
40  end
41
42protected
43  # Creates the shortcuts `text :foo` => `field :text, :foo`
44  Ion::Indices.names.each do |type|
45    define_method(type) do |id, options={}, &blk|
46      field type, id, options, &blk
47    end
48  end
49
50  def field(type, id, options={}, &blk)
51    index_type = Ion::Indices.get(type)
52    @indices[type.to_sym][id.to_sym] = index_type.new(id.to_sym, self, options, &blk)
53  end
54end
55