Module: SqlLoader::ClassMethods

Defined in:
lib/sql_loader.rb

Instance Method Summary collapse

Instance Method Details

#define_sql_from(file_symbol, options = {}) ⇒ Object

Load the given symbol as a file from RAILS_ROOT/apps/queries/file_symbol.sql. options is a Hash of the following:

  • :as_method: The name of the method you want defined to return the sql query as a string from.

Defaults to :sql.

  • :via: The model that you want the query to be called from. This allows some sanitization, if

this option is not supplied, the query will be executed via ActiveRecord::Base::connection.execute.

In addition the definition of :as_method, another method named excecute_<method_name> will be defined to execute the given query.

The execute_sql method will check if the class responds to the method sql_params and if so, will pass the results along with the query.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/sql_loader.rb', line 20

def define_sql_from(file_symbol, options = {})
  sql = File.read("#{RAILS_ROOT}/app/queries/#{file_symbol}.sql")
  sql_method = options[:as_method] || :sql

  define_method(sql_method) { sql }

  define_method("execute_#{sql_method}") {
    model = options[:via]

    if model
      if self.respond_to?("#{sql_method}_params")
        model.find_by_sql([self.send(sql_method), self.send("#{sql_method}_params")])
      else
        model.find_by_sql(self.send(sql_method))
      end
    else
      ActiveRecord::Base.connection.execute(self.send(sql_method))
    end
  }
end