Class: Hyperactive::IndexBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/hyperactive/record.rb

Overview

A tiny callable class that saves stuff in indexes depending on certain attributes.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ IndexBuilder

Initialize an IndexBuilder giving it an array of attributes that will be indexed.



37
38
39
# File 'lib/hyperactive/record.rb', line 37

def initialize(attributes)
  @attributes = attributes
end

Class Method Details

.get_attribute_key_part(attributes) ⇒ Object

Get the first part of the key, that depends on the attributes.



24
25
26
# File 'lib/hyperactive/record.rb', line 24

def self.get_attribute_key_part(attributes)
  "Hyperactive::IndexBuilder::#{attributes.join(",")}"
end

.get_value_key_part(values) ⇒ Object

Get the last part of the key, that depends on the values.



30
31
32
# File 'lib/hyperactive/record.rb', line 30

def self.get_value_key_part(values)
  "#{values.join(",")}"
end

Instance Method Details

#call(argument, &block) ⇒ Object

Call this IndexBuilder and pass it a block.

If the argument is an Array then we know we are a save hook, otherwise we are a destroy hook.



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/hyperactive/record.rb', line 60

def call(argument, &block)
  yield

  #
  # If the argument is an Array (of old value, new value)
  # then we are a save hook, otherwise a destroy hook.
  #
  if Array === argument
    record = argument.last
    old_record = argument.first
    get_tree_for(old_record).delete(record.record_id)
    get_tree_for(record)[record.record_id] = record
  else
    record = argument
    get_tree_for(record).delete(record.record_id)
  end
end

#get_tree_for(record) ⇒ Object

Get the Tree for the given record.



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/hyperactive/record.rb', line 43

def get_tree_for(record)
  values = @attributes.collect do |att|
    if record.respond_to?(att)
      record.send(att)
    else
      nil
    end
  end
  key = "#{self.class.get_attribute_key_part(@attributes)}::#{self.class.get_value_key_part(values)}"
  return CAPTAIN[key] ||= Tree.get_instance
end