Class: Md::Show::App

Inherits:
Sinatra::Base
  • Object
show all
Defined in:
lib/md/show/app.rb

Instance Method Summary collapse

Instance Method Details

#cast_result(element) ⇒ Object



78
79
80
81
82
83
84
85
86
87
# File 'lib/md/show/app.rb', line 78

def cast_result(element)
  case element
  when /^\d+\.\d+$/
    element.to_f
  when /^"\d{4}-\d{2}-\d{2}\s.+"$/
    element[1..-2]
  else
    element
  end
end

#cast_results(e) ⇒ Object



72
73
74
75
76
# File 'lib/md/show/app.rb', line 72

def cast_results(e)
  return [] unless e
  return e unless e.start_with?("{") && e.end_with?("}")
  e[1..-2].split(",").map{|f|cast_result(f)}
end

#connect_to_dbObject

Connect to the PostgreSQL database using the URI provided



10
11
12
13
14
15
# File 'lib/md/show/app.rb', line 10

def connect_to_db
  conn = PG.connect(pg_uri)
  yield conn
ensure
  conn.close if conn
end

#parse_aggregated_results(data) ⇒ Object



66
67
68
69
70
# File 'lib/md/show/app.rb', line 66

def parse_aggregated_results(data)
  data.map do |hash|
    hash.transform_values{|e|JSON.parse(e) rescue cast_results(e)}
  end
end

#pg_uriObject



6
7
8
# File 'lib/md/show/app.rb', line 6

def pg_uri
  ARGV.size == 1 ? ENV['PG_URI'] : ARGV.last
end

#render_markdown(file_path) ⇒ Object

Render the markdown file to HTML using Redcarpet



18
19
20
21
22
# File 'lib/md/show/app.rb', line 18

def render_markdown(file_path)
  markdown = File.read(file_path)
  renderer = Redcarpet::Markdown.new(Redcarpet::Render::HTML)
  renderer.render(markdown)
end

#run_query(conn, sql) ⇒ Object

Run the SQL code snippet and return the result



26
27
28
29
30
31
32
# File 'lib/md/show/app.rb', line 26

def run_query(conn, sql)
  #return if sql !~ /^\s*SELECT\t/i
  result = conn.exec(sql)
  response = result.map(&:to_h)
  puts({sql: sql, response: response})
  response
end