Class: Domain::Model

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}) ⇒ Model

Returns a new instance of Model.



7
8
9
10
11
12
# File 'lib/domain/model.rb', line 7

def initialize(attributes = {})
  attributes.each do |k, v|
    key = "#{k}="
    send(key, v) if respond_to?(key)
  end
end

Class Method Details

.columnsObject

Ensure the columns method retrieves only valid attribute names



31
32
33
34
35
36
# File 'lib/domain/model.rb', line 31

def self.columns
  instance_methods.select { |m| m.to_s.end_with?('=') }
                  .map { |setter| setter.to_s.chomp('=') }
                  .select { |attr| instance_methods.include?(attr.to_sym) && !Object.instance_methods.include?(attr.to_sym) }
                  .sort
end

.from_csv(row) ⇒ Object



57
58
59
# File 'lib/domain/model.rb', line 57

def self.from_csv(row)
  from_json(row.to_h)
end

.from_json(data) ⇒ Object



50
51
52
53
54
55
# File 'lib/domain/model.rb', line 50

def self.from_json(data)
  transformed_data = data.transform_keys do |key|
    key.to_s.underscore.to_sym
  end
  new(transformed_data)
end

.headersObject



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

def self.headers
  columns.join ','
end

.primary_keyObject



26
27
28
# File 'lib/domain/model.rb', line 26

def self.primary_key
  ['id']
end

.table_nameObject



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

def self.table_name
  name.underscore
end

.viewObject



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

def self.view
  "#{table_name}_view"
end

Instance Method Details

#to_csvObject



21
22
23
24
# File 'lib/domain/model.rb', line 21

def to_csv
  self.class.columns
      .map { |column| send(column.to_sym) }
end

#to_hashObject

Convert instance attributes to a hash



15
16
17
18
19
# File 'lib/domain/model.rb', line 15

def to_hash
  self.class.columns.each_with_object({}) do |attr, hash|
    hash[attr] = send(attr.to_sym)
  end
end

#to_sObject



61
62
63
# File 'lib/domain/model.rb', line 61

def to_s
  self.class.columns.map { |attr| send(attr) }.join(',')
end