Module: Rush::FindBy

Included in:
Array
Defined in:
lib/rush/find_by.rb

Overview

Generic find_by (returns first match) and find_all_by (returns all matches) against arrays.

Examples:

processes.find_by_pid(::Process.pid)
processes.find_all_by_cmdline(/mongrel_rails/)

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(meth, *args) ⇒ Object



10
11
12
13
14
15
16
17
18
# File 'lib/rush/find_by.rb', line 10

def method_missing(meth, *args)
	if m = meth.to_s.match(/^find_by_([a-z_]+)$/)
		find_by(m[1], args.first)
	elsif m = meth.to_s.match(/^find_all_by_([a-z_]+)$/)
		find_all_by(m[1], args.first)
	else
		super
	end
end

Instance Method Details

#compare_or_match(value, against) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/rush/find_by.rb', line 32

def compare_or_match(value, against)
	if against.class == Regexp
		value.match(against) ? true : false
	else
		value == against
	end
end

#find_all_by(field, arg) ⇒ Object



26
27
28
29
30
# File 'lib/rush/find_by.rb', line 26

def find_all_by(field, arg)
	select do |item|
		item.respond_to?(field) and compare_or_match(item.send(field), arg)
	end
end

#find_by(field, arg) ⇒ Object



20
21
22
23
24
# File 'lib/rush/find_by.rb', line 20

def find_by(field, arg)
	detect do |item|
		item.respond_to?(field) and compare_or_match(item.send(field), arg)
	end
end