Class: Reins::Model::Relation
- Inherits:
-
Object
- Object
- Reins::Model::Relation
- Includes:
- Enumerable
- Defined in:
- lib/reins/model/relation.rb
Instance Method Summary collapse
- #count ⇒ Object
- #each ⇒ Object
- #first ⇒ Object
-
#initialize(model) ⇒ Relation
constructor
A new instance of Relation.
- #initialize_copy(_other) ⇒ Object
- #last ⇒ Object
- #limit(value) ⇒ Object
- #offset(value) ⇒ Object
- #order(*args) ⇒ Object
- #pluck(field) ⇒ Object
- #to_a ⇒ Object
- #where(*args) ⇒ Object
Constructor Details
#initialize(model) ⇒ Relation
Returns a new instance of Relation.
6 7 8 9 10 11 12 |
# File 'lib/reins/model/relation.rb', line 6 def initialize(model) @model = model @wheres = [] @orders = [] @limit = nil @offset = nil end |
Instance Method Details
#count ⇒ Object
54 55 56 57 58 |
# File 'lib/reins/model/relation.rb', line 54 def count sql, params = build_sql("SELECT COUNT(*) AS c", apply_clauses: true, suppress_order: true) result = Reins::Database.connection.execute(sql, params) first_value(result) end |
#each ⇒ Object
36 37 38 |
# File 'lib/reins/model/relation.rb', line 36 def each(&) to_a.each(&) end |
#first ⇒ Object
44 45 46 |
# File 'lib/reins/model/relation.rb', line 44 def first spawn { |r| r.instance_variable_set(:@limit, 1) }.to_a.first end |
#initialize_copy(_other) ⇒ Object
14 15 16 17 18 |
# File 'lib/reins/model/relation.rb', line 14 def initialize_copy(_other) @wheres = @wheres.dup @orders = @orders.dup @to_a = nil end |
#last ⇒ Object
48 49 50 51 52 |
# File 'lib/reins/model/relation.rb', line 48 def last return to_a.last unless @orders.empty? spawn { |r| r.instance_variable_set(:@orders, [reverse_order]) }.first end |
#limit(value) ⇒ Object
28 29 30 |
# File 'lib/reins/model/relation.rb', line 28 def limit(value) spawn { |r| r.instance_variable_set(:@limit, value) } end |
#offset(value) ⇒ Object
32 33 34 |
# File 'lib/reins/model/relation.rb', line 32 def offset(value) spawn { |r| r.instance_variable_set(:@offset, value) } end |
#order(*args) ⇒ Object
24 25 26 |
# File 'lib/reins/model/relation.rb', line 24 def order(*args) spawn { |r| r.send(:add_order, args) } end |
#pluck(field) ⇒ Object
60 61 62 63 64 |
# File 'lib/reins/model/relation.rb', line 60 def pluck(field) sql, params = build_sql("SELECT #{field}", apply_clauses: true) result = Reins::Database.connection.execute(sql, params) result.map { |row| row.is_a?(Hash) ? row[field.to_s] : row[0] } end |
#to_a ⇒ Object
40 41 42 |
# File 'lib/reins/model/relation.rb', line 40 def to_a @to_a ||= execute_query end |
#where(*args) ⇒ Object
20 21 22 |
# File 'lib/reins/model/relation.rb', line 20 def where(*args) spawn { |r| r.send(:add_where, args) } end |