Class: Relation

Inherits:
Object show all
Defined in:
lib/laris/larisrecord/relation.rb

Constant Summary collapse

SQL_COMMANDS =
{
  select: 'SELECT',
  from: 'FROM',
  joins: 'JOIN',
  where: 'WHERE',
  order: 'ORDER BY',
  limit: 'LIMIT'
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, values = [], sql_clauses = {}) ⇒ Relation

Returns a new instance of Relation.



14
15
16
17
18
19
# File 'lib/laris/larisrecord/relation.rb', line 14

def initialize(klass, values = [], sql_clauses = {})
  @klass = klass
  @values = values
  @sql_clauses = sql_defaults.merge(sql_clauses)
  @cache = nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &blk) ⇒ Object



21
22
23
24
# File 'lib/laris/larisrecord/relation.rb', line 21

def method_missing(method, *args, &blk)
  query if cache.nil?
  cache.send(method, *args, &blk)
end

Instance Attribute Details

#cacheObject

Returns the value of attribute cache.



12
13
14
# File 'lib/laris/larisrecord/relation.rb', line 12

def cache
  @cache
end

#klassObject (readonly)

Returns the value of attribute klass.



11
12
13
# File 'lib/laris/larisrecord/relation.rb', line 11

def klass
  @klass
end

#sql_clausesObject (readonly)

Returns the value of attribute sql_clauses.



11
12
13
# File 'lib/laris/larisrecord/relation.rb', line 11

def sql_clauses
  @sql_clauses
end

#valuesObject

Returns the value of attribute values.



12
13
14
# File 'lib/laris/larisrecord/relation.rb', line 12

def values
  @values
end

Instance Method Details

#joins(table, on = nil) ⇒ Object

allows only a single join



36
37
38
39
40
41
42
43
# File 'lib/laris/larisrecord/relation.rb', line 36

def joins(table, on = nil)
  condition = "#{table} ON #{on}"

  sql_clauses[:joins] =
    [sql_clauses[:joins], condition].compact.join(' JOIN ')

  self
end

#limit(n) ⇒ Object



45
46
47
48
# File 'lib/laris/larisrecord/relation.rb', line 45

def limit(n)
  sql_clauses[:limit] = n
  self
end

#order(column, direction = 'ASC') ⇒ Object



30
31
32
33
# File 'lib/laris/larisrecord/relation.rb', line 30

def order(column, direction = 'ASC')
  sql_clauses[:order] = "#{table_name}.#{column} #{direction}"
  self
end

#reload!Object



26
27
28
# File 'lib/laris/larisrecord/relation.rb', line 26

def reload!
  query
end

#where(conditions) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/laris/larisrecord/relation.rb', line 50

def where(conditions)
  new_fragments = conditions.map do |attr_name, value|
    values << value
    "#{table_name}.#{attr_name} = ?"
  end

  where_fragments = new_fragments.unshift(sql_clauses[:where])
  sql_clauses[:where] = where_fragments.compact.join(" AND ")

  self
end