Class: SqlQuery

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

Defined Under Namespace

Classes: Config

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_name, options = {}) ⇒ SqlQuery

Returns a new instance of SqlQuery.



6
7
8
9
10
11
12
13
# File 'lib/sql_query.rb', line 6

def initialize(file_name, options = {})
  unless file_name.is_a?(String) || file_name.is_a?(Symbol)
    fail ArgumentError, 'SQL file name should be String or Symbol'
  end
  @sql_filename = file_name
  prepare_variables(options)
  @connection = ActiveRecord::Base.connection
end

Instance Attribute Details

#connectionObject (readonly)

Returns the value of attribute connection.



4
5
6
# File 'lib/sql_query.rb', line 4

def connection
  @connection
end

Class Method Details

.configObject



45
46
47
# File 'lib/sql_query.rb', line 45

def self.config
  @config ||= Config.new
end

.config=(value) ⇒ Object



41
42
43
# File 'lib/sql_query.rb', line 41

def self.config=(value)
  @config = value
end

.configure {|config| ... } ⇒ Object

Yields:



49
50
51
# File 'lib/sql_query.rb', line 49

def self.configure
  yield(config)
end

Instance Method Details

#executeObject



21
22
23
# File 'lib/sql_query.rb', line 21

def execute
  connection.execute(prepared_for_logs).entries
end

#explainObject



15
16
17
18
19
# File 'lib/sql_query.rb', line 15

def explain
  msg = "EXPLAIN for: \n#{ sql }\n"
  msg += connection.explain(sql)
  pretty(msg)
end

#prepared_for_logsObject



37
38
39
# File 'lib/sql_query.rb', line 37

def prepared_for_logs
  sql.gsub(/(\n|\s)+/,' ')
end

#pretty_sqlObject



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

def pretty_sql
  pretty(sql.dup)
end

#quote(value) ⇒ Object



33
34
35
# File 'lib/sql_query.rb', line 33

def quote(value)
  connection.quote(value)
end

#sqlObject



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

def sql
  @sql ||= ERB.new(File.read(file_path)).result(binding)
end