Class: Dbee::KeyPath

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/dbee/key_path.rb

Overview

This class represents a relative path from a model to a column. For example: Say we have a model called “users” which is represented by a “users” table. The “users” table also has a one-to-many relationship with a “phone_numbers” table, which is modeled as a nested model under “users” as “phone_numbers”. Then, to get the column: “area_code”, you would use: “phone_numbers.area_code”. Say the column “name” is located on “users”, you could use the key path: “name”. This also works for deeper nested columns in the same fashion.

Constant Summary collapse

SPLIT_CHAR =
'.'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value) ⇒ KeyPath

Returns a new instance of KeyPath.



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

def initialize(value)
  raise 'Value is required' if value.to_s.empty?

  @value          = value.to_s
  @ancestor_names = value.to_s.split(SPLIT_CHAR)
  @column_name    = @ancestor_names.pop

  freeze
end

Instance Attribute Details

#ancestor_namesObject (readonly)

Returns the value of attribute ancestor_names.



29
30
31
# File 'lib/dbee/key_path.rb', line 29

def ancestor_names
  @ancestor_names
end

#column_nameObject (readonly)

Returns the value of attribute column_name.



29
30
31
# File 'lib/dbee/key_path.rb', line 29

def column_name
  @column_name
end

#valueObject (readonly)

Returns the value of attribute value.



29
30
31
# File 'lib/dbee/key_path.rb', line 29

def value
  @value
end

Class Method Details

.get(obj) ⇒ Object



22
23
24
# File 'lib/dbee/key_path.rb', line 22

def get(obj)
  obj.is_a?(self.class) ? obj : new(obj)
end

Instance Method Details

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



47
48
49
# File 'lib/dbee/key_path.rb', line 47

def ==(other)
  other.to_s == to_s
end

#ancestor_pathsObject



52
53
54
55
56
# File 'lib/dbee/key_path.rb', line 52

def ancestor_paths
  ancestor_names.each_with_object([]) do |ancestor, memo|
    memo << [memo.last, ancestor].compact.join(SPLIT_CHAR)
  end
end

#hashObject



43
44
45
# File 'lib/dbee/key_path.rb', line 43

def hash
  value.hash
end