Module: Sequel::Plugins::ActiveRecord::FinderMethods

Defined in:
lib/sequel/plugins/active_record/finder_methods.rb

Constant Summary collapse

DatasetMethods =
FinderMethods
ClassMethods =
FinderMethods

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, **kwargs, &block) ⇒ Object

Implements find_by methods



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/sequel/plugins/active_record/finder_methods.rb', line 7

def method_missing(name, *args, **kwargs, &block)

	strict = name.to_s.ends_with?("!")

	case name

	# Emulate find_by
	when :find_by, :find_by!
		dataset = self.where(*args)
		result = dataset.[](**kwargs)
		raise Sequel::NoMatchingRow.new(dataset) if strict && !result
		result

	# Emulate dynamic finders
	when /^find_by_/
		terms = name.to_s.sub("find_by_", "").chomp("!").split("_and_").map(&:to_sym)
		raise ::ArgumentError, "wrong number of arguments (given #{args.count}, expected #{terms.count})" unless args.count == terms.count
		dataset = self.where(terms.zip(args).to_h)
		result = dataset.first
		raise Sequel::NoMatchingRow.new(dataset) if strict && !result
		result

	# Move up the chain
	else
		super
	end

end