Class: ActiveHash::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/active_repository/write_support.rb

Direct Known Subclasses

ActiveRepository::Base

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Base

Returns a new instance of Base.



6
7
8
9
10
11
12
# File 'lib/active_repository/write_support.rb', line 6

def initialize(attributes = {})
  attributes = attributes.symbolize_keys
  @attributes = attributes
  attributes.dup.each do |key, value|
    send "#{key}=", value
  end
end

Class Method Details

.insert(record) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/active_repository/write_support.rb', line 14

def self.insert(record)
  record_id   = record.id.to_s
  record_hash = record.hash

  remove(record)

  if record_index[record_id].nil? || !self.all.map(&:hash).include?(record_hash)
    insert_record(record)
  end
end

.remove(record) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/active_repository/write_support.rb', line 25

def self.remove(record)
  record_id   = record.id.to_s
  record_hash = record.hash

  if self.all.map(&:hash).include?(record_hash)
    record_index.delete(record_id)
    self.all.delete(record)
  end
end

.validate_unique_id(record) ⇒ Object

Raises:

  • (IdError)


35
36
37
# File 'lib/active_repository/write_support.rb', line 35

def self.validate_unique_id(record)
  raise IdError.new("Duplicate Id found for record #{record.attributes}") if record_index.has_key?(record.id.to_s)
end

Instance Method Details

#deleteObject



56
57
58
59
60
61
62
# File 'lib/active_repository/write_support.rb', line 56

def delete
  record = self.class.find_by(id: self.id)

  self.class.remove(self)

  self.class.find_by(id: self.id).nil?
end

#eql?(other) ⇒ Boolean Also known as: ==

Returns:

  • (Boolean)


73
74
75
# File 'lib/active_repository/write_support.rb', line 73

def eql?(other)
  (other.instance_of?(self.class) || other.instance_of?(persistence_class)) && id.present? && (id == other.id) && (!self.respond_to?(:created_at) || (created_at == other.created_at))
end

#persisted?Boolean

Returns:

  • (Boolean)


68
69
70
71
# File 'lib/active_repository/write_support.rb', line 68

def persisted?
  other = self.class.find_by(id: id)
  other.present?
end

#readonly?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/active_repository/write_support.rb', line 39

def readonly?
  false
end

#save(*args) ⇒ Object



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

def save(*args)
  if self.valid?
    record = self.class.find_by(id: self.id)

    self.class.insert(self) if record.nil? && record != self

    self.id = self.class.last.id if self.id.nil?
    true
  else
    false
  end
end

#to_paramObject



64
65
66
# File 'lib/active_repository/write_support.rb', line 64

def to_param
  id.present? ? id.to_s : nil
end