Class: Partitional::Model

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model
Defined in:
lib/partitional/model.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#mappingObject


64
65
66
# File 'lib/partitional/model.rb', line 64

def mapping
  @mapping || {}
end

#recordObject

Returns the value of attribute record


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

def record
  @record
end

Class Method Details

.attr_accessor(*attrs) ⇒ Object


39
40
41
42
# File 'lib/partitional/model.rb', line 39

def self.attr_accessor(*attrs)
  attr_reader(*attrs)
  attr_writer(*attrs)
end

.attr_define(*attrs) ⇒ Object


14
15
16
17
# File 'lib/partitional/model.rb', line 14

def self.attr_define(*attrs)
  attributes.concat(attrs.map(&:to_sym))
  attributes.uniq!
end

.attr_reader(*attrs) ⇒ Object


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

def self.attr_reader(*attrs)
  attr_define(*attrs)
  attrs.each do |attr|
    attr = attr.to_s.to_sym
    define_method(attr) do
      self[attr]
    end
  end
end

.attr_writer(*attrs) ⇒ Object


29
30
31
32
33
34
35
36
37
# File 'lib/partitional/model.rb', line 29

def self.attr_writer(*attrs)
  attr_define(*attrs)
  attrs.each do |attr|
    attr = attr.to_s.to_sym
    define_method(:"#{attr}=") do |val|
      self[attr] = val
    end
  end
end

.attributesObject


10
11
12
# File 'lib/partitional/model.rb', line 10

def self.attributes
  @attributes ||= []
end

Instance Method Details

#[](attr) ⇒ Object


44
45
46
47
48
# File 'lib/partitional/model.rb', line 44

def [](attr)
  attr = attr.to_s.to_sym
  reader = mapping.fetch(attr) { attr }
  record ? record_send(reader) : instance_variable_get(:"@#{attr}")
end

#[]=(attr, val) ⇒ Object


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

def []=(attr, val)
  attr = attr.to_s.to_sym
  writer = mapping.fetch(attr) { attr }
  record ? record_send(:"#{writer}=", val) : instance_variable_set(:"@#{attr}", val)
end

#as_jsonObject


56
57
58
59
60
61
62
# File 'lib/partitional/model.rb', line 56

def as_json
  attrs = self.class.attributes.map do |key|
    [key, send(key)]
  end

  Hash[attrs]
end