Class: GitModel::Index

Inherits:
Object
  • Object
show all
Defined in:
lib/gitmodel/index.rb

Instance Method Summary collapse

Constructor Details

#initialize(model_class) ⇒ Index

Returns a new instance of Index.



3
4
5
# File 'lib/gitmodel/index.rb', line 3

def initialize(model_class)
  @model_class = model_class
end

Instance Method Details

#attr_index(attr) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/gitmodel/index.rb', line 20

def attr_index(attr)
  self.load unless @indexes
  return nil unless @indexes # this is just so that we can stub self.load in tests

  ret = @indexes[attr.to_s] 
  raise GitModel::AttributeNotIndexed.new(attr.to_s) unless ret
  return ret
end

#filenameObject



29
30
31
# File 'lib/gitmodel/index.rb', line 29

def filename
  File.join(@model_class.db_subdir, '_indexes.json')
end

#generate!Object



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/gitmodel/index.rb', line 7

def generate!
  GitModel.logger.debug "Generating indexes for #{@model_class}"
  # TODO it sucks to load every instance here, optimize later
  @indexes = {}
  @model_class.find_all.each do |o|
    o.attributes.each do |attr, value|
      @indexes[attr] ||= {}
      @indexes[attr][value] ||= SortedSet.new
      @indexes[attr][value] << o.id
    end
  end
end

#generated?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/gitmodel/index.rb', line 33

def generated?
  (GitModel.current_tree / filename) ? true : false
end

#loadObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/gitmodel/index.rb', line 55

def load
  unless generated?
    GitModel.logger.debug "No index generated for #{@model_class}, not loading."
    return
  end

  GitModel.logger.debug "Loading indexes for #{@model_class}..."
  @indexes = {}
  blob = GitModel.current_tree / filename
  
  data = Yajl::Parser.parse(blob.data)
  data.each do |attr_and_values|
    attr = attr_and_values[0]
    values = {}
    attr_and_values[1].each do |value_and_ids|
      value = value_and_ids[0]
      ids = SortedSet.new(value_and_ids[1])
      values[value] = ids
    end
    @indexes[attr] = values
  end
end

#save(options = {}) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/gitmodel/index.rb', line 37

def save(options = {})
  GitModel.logger.debug "Saving indexes for #{@model_class}..."
  transaction = options.delete(:transaction) || GitModel::Transaction.new(options) 
  result = transaction.execute do |t|
    # convert to array because JSON hash keys must be strings
    data = []
    @indexes.each do |attr,values|
      values_and_ids = []
      values.each do |value, ids|
        values_and_ids << [value, ids.to_a]
      end
      data << [attr,values_and_ids]
    end
    data = Yajl::Encoder.encode(data, nil, :pretty => true)
    t.index.add(filename, data)
  end
end