Class: Dis::Model::Data

Inherits:
Object
  • Object
show all
Defined in:
lib/dis/model/data.rb

Overview

Dis Model Data

Facilitates communication between the model and the storage, and holds any newly assigned data before the record is saved.

Instance Method Summary collapse

Constructor Details

#initialize(record, raw = nil) ⇒ Data

Returns a new instance of Data.



10
11
12
13
# File 'lib/dis/model/data.rb', line 10

def initialize(record, raw = nil)
  @record = record
  @raw = raw
end

Instance Method Details

#==(other) ⇒ Object

Returns true if two Data objects represent the same data.



16
17
18
19
20
# File 'lib/dis/model/data.rb', line 16

def ==(other)
  # TODO: This can be made faster by
  # comparing hashes for stored objects.
  other.read == read
end

#any?Boolean

Returns true if data exists either in memory or in storage.

Returns:

  • (Boolean)


23
24
25
# File 'lib/dis/model/data.rb', line 23

def any?
  raw? || stored?
end

#changed?Boolean

Will be true if data has been explicitely set.

Dis::Model::Data.new(record).changed? # => false
Dis::Model::Data.new(record, new_file).changed? # => true

Returns:

  • (Boolean)


36
37
38
# File 'lib/dis/model/data.rb', line 36

def changed?
  raw?
end

#content_lengthObject

Returns the length of the data.



41
42
43
44
45
46
47
# File 'lib/dis/model/data.rb', line 41

def content_length
  if raw? && raw.respond_to?(:length)
    raw.length
  else
    read.try(&:length).to_i
  end
end

#expire(hash) ⇒ Object

Expires a data object from the storage if it’s no longer being used by existing records. This is triggered from callbacks on the record whenever they are changed or destroyed.



52
53
54
55
56
57
58
# File 'lib/dis/model/data.rb', line 52

def expire(hash)
  unless @record.class.where(
    @record.class.dis_attributes[:content_hash] => hash
  ).any?
    Dis::Storage.delete(storage_type, hash)
  end
end

#readObject

Returns the data as a binary string.



28
29
30
# File 'lib/dis/model/data.rb', line 28

def read
  @read ||= read_from(closest)
end

#store!Object

Stores the data. Returns a hash of the content for reference.



61
62
63
64
65
# File 'lib/dis/model/data.rb', line 61

def store!
  raise Dis::Errors::NoDataError unless raw?

  Dis::Storage.store(storage_type, raw)
end