Class: Hyperactive::Index::IndexBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/hyperactive/index.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(klass, attributes) ⇒ IndexBuilder

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



45
46
47
48
# File 'lib/hyperactive/index.rb', line 45

def initialize(klass, attributes)
  @klass = klass
  @attributes = attributes
end

Class Method Details

.get_key(klass, attributes, values) ⇒ Object

Get the key for the given attributes and values.



38
39
40
# File 'lib/hyperactive/index.rb', line 38

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

Instance Method Details

#call(*arguments, &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.



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/hyperactive/index.rb', line 68

def call(*arguments, &block)
  yield

  #
  # If the argument is an Array (of old value, new value)
  # then we are a save hook, otherwise a destroy hook.
  #
  if arguments.size > 1
    record = arguments.first
    old_record = arguments.last
    old_key = get_key_for(old_record)
    new_key = get_key_for(record)
    if old_key != new_key
      (Archipelago::Pirate::BLACKBEARD[old_key] ||= Hyperactive::Hash::Head.get_instance_with_transaction(record.transaction)).delete(record.record_id)
      (Archipelago::Pirate::BLACKBEARD[new_key] ||= Hyperactive::Hash::Head.get_instance_with_transaction(record.transaction))[record.record_id] = record
    end
  else
    record = arguments.first
    (Archipelago::Pirate::BLACKBEARD[get_key_for(record)] ||= Hyperactive::Hash::Head.get_instance_with_transaction(record.transaction)).delete(record.record_id)
  end
end

#get_key_for(record) ⇒ Object

Get the key for the given record.



52
53
54
55
56
57
58
59
60
61
# File 'lib/hyperactive/index.rb', line 52

def get_key_for(record)
  values = @attributes.collect do |att|
    if record.respond_to?(att)
      record.send(att)
    else
      nil
    end
  end
  key = self.class.get_key(@klass, @attributes, values)
end