/lib/ion/options.rb

http://github.com/rstacruz/ion · Ruby · 55 lines · 38 code · 11 blank · 6 comment · 1 complexity · cf549533b389ab4cd4fcaf8df921450f MD5 · raw file

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