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
14
# 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
  @options = options
  @connection =  options.try(:delete, :db_connection) || self.class.config.adapter.connection
  prepare_variables
end

Instance Attribute Details

#config=(value) ⇒ Object (writeonly)

Sets the attribute config

Parameters:

  • value

    the value to set the attribute config to.



51
52
53
# File 'lib/sql_query.rb', line 51

def config=(value)
  @config = value
end

#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



52
53
54
# File 'lib/sql_query.rb', line 52

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

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

Yields:



56
57
58
# File 'lib/sql_query.rb', line 56

def self.configure
  yield(config)
end

Instance Method Details

#execute(prepare = true) ⇒ Object



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

def execute(prepare = true)
  to_execute = prepare ? prepared_for_logs : sql
  connection.execute(to_execute).entries
end

#explainObject



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

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

#partial(partial_name, partial_options = {}) ⇒ Object



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

def partial(partial_name, partial_options = {})
  path, file_name = split_to_path_and_name(partial_name)
  self.class.new("#{path}/_#{file_name}",
                 @options.merge(partial_options),
                ).sql
end

#prepared_for_logsObject



39
40
41
# File 'lib/sql_query.rb', line 39

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

#pretty_sqlObject



31
32
33
# File 'lib/sql_query.rb', line 31

def pretty_sql
  pretty(sql.dup)
end

#quote(value) ⇒ Object



35
36
37
# File 'lib/sql_query.rb', line 35

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

#sqlObject



27
28
29
# File 'lib/sql_query.rb', line 27

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