Class: Simple::SQL::Scope

Inherits:
Object
  • Object
show all
Defined in:
lib/simple/sql/scope.rb

Overview

The Simple::SQL::Scope class helps building scopes; i.e. objects that start as a quite basic SQL query, and allow one to add sql_fragments as where conditions.

Defined Under Namespace

Modules: PageInfo

Constant Summary collapse

SELF =
self

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sql) ⇒ Scope

Build a scope object



19
20
21
22
23
# File 'lib/simple/sql/scope.rb', line 19

def initialize(sql)
  @sql = sql
  @args = []
  @filters = []
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



15
16
17
# File 'lib/simple/sql/scope.rb', line 15

def args
  @args
end

#pageObject (readonly)

Returns the value of attribute page.



16
17
18
# File 'lib/simple/sql/scope.rb', line 16

def page
  @page
end

#perObject (readonly)

Returns the value of attribute per.



16
17
18
# File 'lib/simple/sql/scope.rb', line 16

def per
  @per
end

Instance Method Details

#paginate(per:, page:) ⇒ Object

Set pagination



68
69
70
# File 'lib/simple/sql/scope.rb', line 68

def paginate(per:, page:)
  duplicate.send(:paginate!, per: per, page: page)
end

#paginated?Boolean

Is this a paginated scope?

Returns:

  • (Boolean)


84
85
86
# File 'lib/simple/sql/scope.rb', line 84

def paginated?
  not @per.nil?
end

#to_sql(pagination: :auto) ⇒ Object

generate a sql query

Raises:

  • (ArgumentError)


89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/simple/sql/scope.rb', line 89

def to_sql(pagination: :auto)
  raise ArgumentError unless pagination == :auto || pagination == false

  sql = @sql
  active_filters = @filters.compact
  unless active_filters.empty?
    sql += " WHERE (" + active_filters.join(") AND (") + ")"
  end
  if pagination == :auto && @per && @page
    raise ArgumentError, "per must be > 0" unless @per > 0
    raise ArgumentError, "page must be > 0" unless @page > 0

    sql += "LIMIT #{@per} OFFSET #{(@page - 1) * @per}"
  end

  sql
end

#where(sql_fragment, arg = :__dummy__no__arg, placeholder: "?") ⇒ Object

scope = Scope.new(“SELECT * FROM tablename”) scope = scope.where(“id > ?”, 12)

The placeholder (usually a ‘?’) is being replaced with the numbered argument (since postgres is using $1, $2, etc.) If your SQL fragment uses ‘?’ as part of some fixed text you must use an alternative placeholder symbol.

TODO: Add support for hash arguments, i.e. scope = scope.where(title: “foobar”)



48
49
50
# File 'lib/simple/sql/scope.rb', line 48

def where(sql_fragment, arg = :__dummy__no__arg, placeholder: "?")
  duplicate.send(:where!, sql_fragment, arg, placeholder: placeholder)
end