Class: DataMapper::Unlazy::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/dm-unlazy/collection.rb

Instance Method Summary collapse

Constructor Details

#initialize(collection) ⇒ Collection

Returns a new instance of Collection.



24
25
26
27
28
29
30
# File 'lib/dm-unlazy/collection.rb', line 24

def initialize (collection)
	unless collection.is_a?(DataMapper::Collection)
		raise ArgumentError, 'you have to pass a Collection'
	end

	@collection = collection
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(id, *args, &block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/dm-unlazy/collection.rb', line 32

def method_missing (id, *args, &block)
	collection = @collection

	if (Array.instance_method(id) rescue false)
		reload unless @resources

		if @resources.is_a?(Array)
			return @resources.__send__ id, *args, &block
		end

		collection = @resources
	end

	result = collection.__send__ id, *args, &block

	if result.is_a?(DataMapper::Collection)
		Collection.new(result)
	else
		result
	end
end

Instance Method Details

#fields(*fields) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/dm-unlazy/collection.rb', line 54

def fields (*fields)
	@fields = fields.flatten.map(&:to_sym)
	@fields.push *model.key.entries.map(&:name)
	@fields.uniq!

	self
end

#reloadObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/dm-unlazy/collection.rb', line 62

def reload
	adapter    = repository.adapter
	collection = @collection.all(:fields => @fields || model.properties.map(&:field))

	if adapter.respond_to? :select
		statement = adapter.send(:select_statement, collection.query).flatten(1)

		@resources = adapter.select(*statement).map {|data|
			if data.is_a?(Struct)
				Unlazy::Model.new(model, data)
			else
				Unlazy::Model.new(model, Struct.new(@fields.first).new(data))
			end
		}
	else
		@resources = collection
	end

	self
end