Class: Yaasql::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/yaasql/reader.rb

Constant Summary collapse

HEADER_PATTERN =
/^-- name: (.*)\n/

Instance Method Summary collapse

Instance Method Details

#arguments(body) ⇒ Object



25
26
27
# File 'lib/yaasql/reader.rb', line 25

def arguments(body)
  body.scan(/:(\w+);?/).flatten.map(&:to_sym)
end

#components(query) ⇒ Object



29
30
31
32
33
34
# File 'lib/yaasql/reader.rb', line 29

def components(query)
  name = name(query)
  body = raw_body(query)
  arguments = arguments(body)
  {name: name, body: with_sql_args(body, arguments), arguments: arguments}
end

#from_file(path) ⇒ Object



36
37
38
39
# File 'lib/yaasql/reader.rb', line 36

def from_file(path)
  query_strings = File.read(path).split("\n\n")
  query_strings.map { |q| Query.new(components(q)) }
end

#name(query) ⇒ Object



4
5
6
7
8
9
10
11
# File 'lib/yaasql/reader.rb', line 4

def name(query)
  match = query.match(HEADER_PATTERN)
  if match
    match[1].to_sym
  else
    raise ArgumentError.new("Must provide a header comment with query name")
  end
end

#raw_body(query) ⇒ Object



13
14
15
16
17
# File 'lib/yaasql/reader.rb', line 13

def raw_body(query)
  query.split("\n").map(&:strip).reject do |line|
    line.start_with?('--')
  end.join('\n')
end

#with_sql_args(body, arguments) ⇒ Object



19
20
21
22
23
# File 'lib/yaasql/reader.rb', line 19

def with_sql_args(body, arguments)
  arguments.each.with_index.reduce(body) do |body, (arg, index)|
    body.gsub(":#{arg}", "$#{index+1}")
  end
end