Class: Rel::Model

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

Constant Summary collapse

@@fields =
Hash.new { |hash, key| hash[key] = {} }

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ Model

Returns a new instance of Model.



11
12
13
14
15
16
# File 'lib/rel/model.rb', line 11

def initialize(attrs = {})
  attrs.each do |field, value|
    name, type = field.to_s.split(":")
    send(:"#{name}=", value)
  end
end

Class Method Details

.field(name, type) ⇒ Object



6
7
8
9
# File 'lib/rel/model.rb', line 6

def self.field(name, type)
  @@fields[self.name][name] = type
  attr_accessor name
end

Instance Method Details

#fieldsObject



41
42
43
# File 'lib/rel/model.rb', line 41

def fields
  @@fields[self.class.name]
end

#headerObject



35
36
37
38
39
# File 'lib/rel/model.rb', line 35

def header
  fields.map do |field, type|
    "#{field}:#{type}"
  end
end

#to_hashObject



18
19
20
21
22
23
24
25
26
27
# File 'lib/rel/model.rb', line 18

def to_hash
  record = []

  header.zip(values) do |field, value|
    record << field
    record << value
  end

  Hash[*record]
end

#valuesObject



29
30
31
32
33
# File 'lib/rel/model.rb', line 29

def values
  fields.map do |field, _|
    send(field)
  end
end