Class: Dbee::Model

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/dbee/model.rb,
lib/dbee/model/constraints.rb,
lib/dbee/model/constraints/base.rb,
lib/dbee/model/constraints/static.rb,
lib/dbee/model/constraints/reference.rb

Overview

In DB terms, a Model is usually a table, but it does not have to be. You can also re-model your DB schema using Dbee::Models.

Defined Under Namespace

Classes: Constraints, ModelNotFoundError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name:, constraints: [], models: [], table: '') ⇒ Model

Returns a new instance of Model.

Raises:

  • (ArgumentError)


33
34
35
36
37
38
39
40
41
42
# File 'lib/dbee/model.rb', line 33

def initialize(name:, constraints: [], models: [], table: '')
  raise ArgumentError, 'name is required' if name.to_s.empty?

  @name           = name.to_s
  @constraints    = Constraints.array(constraints)
  @models_by_name = name_hash(Model.array(models))
  @table          = table.to_s.empty? ? @name : table.to_s

  freeze
end

Instance Attribute Details

#constraintsObject (readonly)

Returns the value of attribute constraints.



25
26
27
# File 'lib/dbee/model.rb', line 25

def constraints
  @constraints
end

#nameObject (readonly)

Returns the value of attribute name.



25
26
27
# File 'lib/dbee/model.rb', line 25

def name
  @name
end

#tableObject (readonly)

Returns the value of attribute table.



25
26
27
# File 'lib/dbee/model.rb', line 25

def table
  @table
end

Instance Method Details

#<=>(other) ⇒ Object



77
78
79
# File 'lib/dbee/model.rb', line 77

def <=>(other)
  name <=> other.name
end

#==(other) ⇒ Object Also known as: eql?



68
69
70
71
72
73
74
# File 'lib/dbee/model.rb', line 68

def ==(other)
  other.instance_of?(self.class) &&
    other.name == name &&
    other.table == table &&
    other.sorted_constraints == sorted_constraints &&
    other.sorted_models == sorted_models
end

#ancestors(parts = [], alias_chain = [], found = {}) ⇒ Object

Raises:



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/dbee/model.rb', line 48

def ancestors(parts = [], alias_chain = [], found = {})
  return found if Array(parts).empty?

  alias_chain = [] if Array(alias_chain).empty?

  model_name = parts.first

  model = models_by_name[model_name.to_s]

  raise ModelNotFoundError, "Cannot traverse: #{model_name}" unless model

  new_alias_chain = alias_chain + [model_name]

  new_alias = new_alias_chain.join(JOIN_CHAR)

  found[new_alias] = model

  model.ancestors(parts[1..-1], new_alias_chain, found)
end

#name_hash(array) ⇒ Object



44
45
46
# File 'lib/dbee/model.rb', line 44

def name_hash(array)
  array.map { |a| [a.name, a] }.to_h
end