Class: Hyperactive::Record::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.



60
61
62
# File 'lib/hyperactive/record.rb', line 60

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.



47
48
49
# File 'lib/hyperactive/record.rb', line 47

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.



53
54
55
# File 'lib/hyperactive/record.rb', line 53

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.



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
# File 'lib/hyperactive/record.rb', line 82

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
    old_key = get_key_for(old_record)
    new_key = get_key_for(record)
    if old_key != new_key
      (CAPTAIN[old_key] ||= Hyperactive::Hash::Head.get_instance_with_transaction(record.transaction)).delete(record.record_id)
      (CAPTAIN[new_key] ||= Hyperactive::Hash::Head.get_instance_with_transaction(record.transaction))[record.record_id] = record
    end
  else
    record = argument
    (CAPTAIN[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.



66
67
68
69
70
71
72
73
74
75
# File 'lib/hyperactive/record.rb', line 66

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_attribute_key_part(@attributes)}::#{self.class.get_value_key_part(values)}"
end