Class: YDB::Row

Inherits:
Object
  • Object
show all
Defined in:
lib/yaml-file-db/row.rb

Constant Summary collapse

INTERNAL_VARS =
%i[@id @source].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, schema_path) ⇒ Row

Returns a new instance of Row.



9
10
11
12
13
14
15
# File 'lib/yaml-file-db/row.rb', line 9

def initialize(source, schema_path)
  @id = File.basename(source, '.yml')
  @source = source

  validate_filename
  build(source, schema_path)
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



7
8
9
# File 'lib/yaml-file-db/row.rb', line 7

def id
  @id
end

#sourceObject (readonly)

Returns the value of attribute source.



7
8
9
# File 'lib/yaml-file-db/row.rb', line 7

def source
  @source
end

Instance Method Details

#build_relationships(db, keywords) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/yaml-file-db/row.rb', line 17

def build_relationships(db, keywords)
  errors = []
  iterate_over_columns do |key, value|
    if keywords.include?(key)
      if key.pluralize == key
        rows = []
        table = db.public_send(key.to_sym)
        value.each do |primary_key|
          row = table[primary_key]
          errors << "Invalid primary_key: #{primary_key} isn't part of table #{key}" if row.nil?
          rows << row
        end
        instance_variable_set("@#{key}", rows)
      else
        row = db.public_send(key.pluralize.to_sym)[value]
        errors << "Invalid primary_key: #{value} isn't part of table #{key.pluralize}" if row.nil?
        instance_variable_set("@#{key}", row)
      end
    end
  end
  errors
end

#check_relationships(_db, keywords) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/yaml-file-db/row.rb', line 40

def check_relationships(_db, keywords)
  errors = []
  iterate_over_columns do |key, value|
    if keywords.include?(key)
      next if value.nil?

      value = [value] if value.is_a?(YDB::Row)
      value.each do |row|
        if row.respond_to?(self.class.to_s.downcase.to_sym)
          unless row.public_send(self.class.to_s.downcase.to_sym) == self
            errors << "Inconsistent relationship: #{row.id} doesn't link back to #{id}"
          end
        elsif row.respond_to?(self.class.to_s.downcase.pluralize.to_sym)
          unless row.public_send(self.class.to_s.downcase.pluralize.to_sym).include?(self)
            errors << "Inconsistent relationship: #{row.id} doesn't link back to #{id}"
          end
        end
      end
    end
  end
  errors
end