Class: PgSqlCaller::Base

Inherits:
Model
  • Object
show all
Includes:
Singleton
Defined in:
lib/pg_sql_caller/base.rb

Overview

Class-level, app-wide facade over a single shared Model instance (a Singleton). Declare the ActiveRecord class once, then call the same SQL methods directly on the class — every call is forwarded to ‘.instance`.

class Sql < PgSqlCaller::Base
  model_class 'ApplicationRecord' # a String (constantized on first use) or the Class itself
end

Sql.select_value('SELECT count(*) FROM users WHERE active = ?', true) # => 42
Sql.transaction { Sql.execute('DELETE FROM logs') }

‘PgSqlCaller::Base` can also be configured and used directly:

PgSqlCaller::Base.model_class ApplicationRecord
PgSqlCaller::Base.current_database # => 'my_db'

Every public Model instance method is available as a class method here.

See Also:

Instance Attribute Summary

Attributes inherited from Model

#model_class

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Model

#connection, #current_database, define_sql_method, define_sql_methods, #execute, #explain_analyze, #next_sequence_value, #quote_column_name, #quote_table_name, #quote_value, #sanitize_sql_array, #select_all, #select_all_serialized, #select_row, #select_rows, #select_value, #select_value_serialized, #select_values, #select_values_serialized, #table_data_size, #table_full_size, #transaction, #transaction_open?, #typecast_array, #with_min_messages, #with_notice_processor

Constructor Details

#initializeBase

Build the singleton instance. Invoked once by instance; never called directly (Singleton makes .new private). Resolves the configured model_class name/class into a Class for Model#model_class.

Raises:

  • (NotImplementedError)

    if model_class was never configured



63
64
65
66
67
# File 'lib/pg_sql_caller/base.rb', line 63

def initialize
  raise NotImplementedError, "define model_class in #{self.class}" if _model_class.nil?

  @model_class = _model_class.is_a?(String) ? _model_class.constantize : _model_class
end

Class Method Details

.instancePgSqlCaller::Base

The shared singleton instance (from Ruby’s Singleton) that every class-level call is delegated to. Built on first access.

Returns:



37
# File 'lib/pg_sql_caller/base.rb', line 37

class_attribute :_model_class, instance_writer: false

.model_class(klass) ⇒ Class<ActiveRecord::Base>, String

Configure which ActiveRecord class backs this caller — the class itself or its name as a String (constantized lazily on first use). Call once, at boot.

PgSqlCaller::Base.model_class ApplicationRecord

Parameters:

  • klass (Class<ActiveRecord::Base>, String)

    the class, or its name

Returns:

  • (Class<ActiveRecord::Base>, String)

    the value just set



47
48
49
# File 'lib/pg_sql_caller/base.rb', line 47

def model_class(klass)
  self._model_class = klass
end