class Solargraph::Arc::Schema

Constants

ColumnData
RUBY_TYPES

Public Class Methods

instance() click to toggle source
# File lib/solargraph/arc/schema.rb, line 20
def self.instance
  @instance ||= self.new
end
new() click to toggle source
# File lib/solargraph/arc/schema.rb, line 24
def initialize
  @schema_present = File.exist?("db/schema.rb")
end

Public Instance Methods

process(source_map, ns) click to toggle source
# File lib/solargraph/arc/schema.rb, line 28
def process(source_map, ns)
  return [] unless @schema_present
  return [] unless source_map.filename.include?("app/models")

  table_name = infer_table_name(ns)
  table      = schema[table_name]

  return [] unless table

  pins = table.map do |column, data|
    Util.build_public_method(
      ns,
      column,
      types: [RUBY_TYPES.fetch(data.type.to_sym)],
      location: Util.build_location(data.ast, "db/schema.rb")
    )
  end

  Solargraph.logger.debug("[ARC][Schema] added #{pins.map(&:name)} to #{ns.path}") if pins.any?
  pins
end

Private Instance Methods

extract_schema(ast) click to toggle source
# File lib/solargraph/arc/schema.rb, line 65
def extract_schema(ast)
  schema = {}

  walker = Walker.new(ast)
  walker.on :block, [:send, nil, :create_table] do |ast, query|
    table_name = ast.children.first.children[2].children.last
    schema[table_name] = {}

    query.on :send, [:lvar, :t] do |column_ast|
      name = column_ast.children[2].children.last
      type = column_ast.children[1]

      next if type == :index
      schema[table_name][name] = ColumnData.new(type, column_ast)
    end
  end

  walker.walk
  schema
end
infer_table_name(ns) click to toggle source

TODO: support custom table names, by parsing ‘self.table_name = ` invokations inside model

# File lib/solargraph/arc/schema.rb, line 61
def infer_table_name(ns)
  ns.name.underscore.pluralize
end
schema() click to toggle source
# File lib/solargraph/arc/schema.rb, line 52
def schema
  @extracted_schema ||= begin
    ast = NodeParser.parse(File.read("db/schema.rb"), "db/schema.rb")
    extract_schema(ast)
  end
end