Class: RareMap::Table

Inherits:
Object
  • Object
show all
Defined in:
lib/rare_map/schema_parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, opts = { :id => true, :primary_key => nil }) ⇒ Table

Returns a new instance of Table.



36
37
38
39
40
41
42
# File 'lib/rare_map/schema_parser.rb', line 36

def initialize(name, opts = { :id => true, :primary_key => nil })
  @name = name
  @id = opts[:id]
  @primary_key = opts[:primary_key]
  @columns = []
  @fk_suffix = 'id'
end

Instance Attribute Details

#columnsObject (readonly)

Returns the value of attribute columns.



32
33
34
# File 'lib/rare_map/schema_parser.rb', line 32

def columns
  @columns
end

#fk_suffixObject

Returns the value of attribute fk_suffix.



34
35
36
# File 'lib/rare_map/schema_parser.rb', line 34

def fk_suffix
  @fk_suffix
end

#idObject (readonly)

Returns the value of attribute id.



32
33
34
# File 'lib/rare_map/schema_parser.rb', line 32

def id
  @id
end

#nameObject (readonly)

Returns the value of attribute name.



32
33
34
# File 'lib/rare_map/schema_parser.rb', line 32

def name
  @name
end

#primary_keyObject



44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rare_map/schema_parser.rb', line 44

def primary_key
  return @primary_key if @primary_key
  return 'id' if @id
  
  candidates = @columns.find_all { |col| col.unique }.map { |col| col.name }
  # return @primary_key if candidates.include? @primary_key
  return 'id' if candidates.include? 'id'
  candidates.find { |c| c =~ eval("/^#{@name}.*id$/") } ||
  candidates.find { |c| c =~ eval("/^#{singularize}.*id$/") } ||
  candidates.find { |c| c =~ eval("/^#{pluralize}.*id$/") } ||
  candidates.first
end

Instance Method Details

#match_foreign_key(column) ⇒ Object



65
66
67
68
69
# File 'lib/rare_map/schema_parser.rb', line 65

def match_foreign_key(column)
  if column.references == @name || foreign_keys.include?(column.name)
    @name if primary_key
  end
end

#match_foreign_key_by_primary_key(pk) ⇒ Object



71
72
73
# File 'lib/rare_map/schema_parser.rb', line 71

def match_foreign_key_by_primary_key(pk)
  @name if foreign_keys.include?(pk) && primary_key
end

#pluralizeObject



61
62
63
# File 'lib/rare_map/schema_parser.rb', line 61

def pluralize
  @name.pluralize
end

#singularizeObject



57
58
59
# File 'lib/rare_map/schema_parser.rb', line 57

def singularize
  @name.pluralize.singularize
end