2009-07-21 23:21:03 +00:00
|
|
|
module ActiveRecord
|
|
|
|
class Relation
|
2009-08-18 11:27:37 +00:00
|
|
|
delegate :to_sql, :to => :relation
|
2009-07-21 23:21:03 +00:00
|
|
|
attr_reader :relation, :klass
|
|
|
|
|
|
|
|
def initialize(klass, table = nil)
|
|
|
|
@klass = klass
|
|
|
|
@relation = Arel::Table.new(table || @klass.table_name)
|
|
|
|
end
|
|
|
|
|
|
|
|
def to_a
|
|
|
|
@klass.find_by_sql(@relation.to_sql)
|
|
|
|
end
|
|
|
|
|
2009-08-03 17:15:47 +00:00
|
|
|
def each(&block)
|
|
|
|
to_a.each(&block)
|
|
|
|
end
|
|
|
|
|
2009-07-21 23:21:03 +00:00
|
|
|
def first
|
|
|
|
@relation = @relation.take(1)
|
|
|
|
to_a.first
|
|
|
|
end
|
|
|
|
|
2009-08-18 10:50:11 +00:00
|
|
|
def select!(selection)
|
|
|
|
@relation = @relation.project(selection) if selection
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2009-08-18 11:27:37 +00:00
|
|
|
def on!(on)
|
|
|
|
@relation = @relation.on(on) if on
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
|
|
|
def order!(order)
|
|
|
|
@relation = @relation.order(order) if order
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
|
|
|
def group!(group)
|
|
|
|
@relation = @relation.group(group) if group
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2009-08-18 10:50:11 +00:00
|
|
|
def limit!(limit)
|
|
|
|
@relation = @relation.take(limit) if limit
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
|
|
|
def offset!(offset)
|
|
|
|
@relation = @relation.skip(offset) if offset
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2009-08-18 11:18:24 +00:00
|
|
|
def joins!(joins, join_type = nil)
|
|
|
|
if !joins.blank?
|
|
|
|
@relation = case joins
|
|
|
|
when String
|
|
|
|
@relation.join(joins)
|
|
|
|
when Hash, Array, Symbol
|
|
|
|
if @klass.send(:array_of_strings?, joins)
|
|
|
|
@relation.join(joins.join(' '))
|
|
|
|
else
|
|
|
|
@relation.join(@klass.send(:build_association_joins, joins))
|
|
|
|
end
|
2009-08-14 15:33:05 +00:00
|
|
|
else
|
2009-08-18 11:18:24 +00:00
|
|
|
@relation.join(joins, join_type)
|
2009-08-14 15:33:05 +00:00
|
|
|
end
|
|
|
|
end
|
2009-07-31 19:08:22 +00:00
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2009-08-18 10:50:11 +00:00
|
|
|
def conditions!(conditions)
|
2009-07-31 19:08:22 +00:00
|
|
|
if !conditions.blank?
|
|
|
|
conditions = @klass.send(:merge_conditions, conditions) if [String, Hash, Array].include?(conditions.class)
|
|
|
|
@relation = @relation.where(conditions)
|
|
|
|
end
|
|
|
|
self
|
|
|
|
end
|
|
|
|
|
2009-07-21 23:21:03 +00:00
|
|
|
private
|
|
|
|
def method_missing(method, *args, &block)
|
|
|
|
if @relation.respond_to?(method)
|
|
|
|
@relation.send(method, *args, &block)
|
|
|
|
elsif Array.instance_methods.include?(method.to_s)
|
|
|
|
to_a.send(method, *args, &block)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|