Class: Sprig::Reap::Model

Inherits:
Object
  • Object
show all
Defined in:
lib/sprig/reap/model.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Model

Returns a new instance of Model.



20
21
22
# File 'lib/sprig/reap/model.rb', line 20

def initialize(klass)
  @klass = klass
end

Instance Attribute Details

#existing_sprig_idsObject



38
39
40
# File 'lib/sprig/reap/model.rb', line 38

def existing_sprig_ids
  @existing_sprig_ids ||= []
end

#klassObject (readonly)

Returns the value of attribute klass.



17
18
19
# File 'lib/sprig/reap/model.rb', line 17

def klass
  @klass
end

Class Method Details

.allObject



3
4
5
6
7
8
9
10
11
# File 'lib/sprig/reap/model.rb', line 3

def self.all
  @@all ||= begin
    models = Sprig::Reap.classes.map { |klass| new(klass) }

    tsorted_classes(models).map do |klass|
      models.find { |model| model.klass == klass }
    end
  end
end

.find(klass, id) ⇒ Object



13
14
15
# File 'lib/sprig/reap/model.rb', line 13

def self.find(klass, id)
  all.find { |model| model.klass == klass }.find(id)
end

Instance Method Details

#associationsObject



32
33
34
35
36
# File 'lib/sprig/reap/model.rb', line 32

def associations
  @associations ||= klass.reflect_on_all_associations(:belongs_to).map do |association|
    Association.new(association)
  end
end

#attributesObject



24
25
26
# File 'lib/sprig/reap/model.rb', line 24

def attributes
  klass.column_names - Sprig::Reap.ignored_attrs
end

#dependenciesObject



28
29
30
# File 'lib/sprig/reap/model.rb', line 28

def dependencies
  @dependencies ||= associations.flat_map(&:dependencies)
end

#find(id) ⇒ Object



46
47
48
# File 'lib/sprig/reap/model.rb', line 46

def find(id)
  records.find { |record| record.id == id }
end

#generate_sprig_idObject



42
43
44
# File 'lib/sprig/reap/model.rb', line 42

def generate_sprig_id
  existing_sprig_ids.select { |i| i.is_a? Integer }.sort.last + 1
end

#recordsObject



67
68
69
# File 'lib/sprig/reap/model.rb', line 67

def records
  @records ||= klass.all.map { |record| Record.new(record, self) }
end

#to_sObject



50
51
52
# File 'lib/sprig/reap/model.rb', line 50

def to_s
  klass.to_s
end

#to_yaml(options = {}) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/sprig/reap/model.rb', line 54

def to_yaml(options = {})
  namespace         = options[:namespace]
  formatted_records = records.map(&:to_hash)

  yaml = if namespace
    { namespace => formatted_records }.to_yaml
  else
    formatted_records.to_yaml
  end

  yaml.gsub("---\n", '') # Remove annoying YAML separator
end