Class: MongoModel::DynamicFinder
- Inherits:
-
Object
- Object
- MongoModel::DynamicFinder
- Defined in:
- lib/mongomodel/support/dynamic_finder.rb
Class Method Summary collapse
Instance Method Summary collapse
- #bang? ⇒ Boolean
- #execute(*args) ⇒ Object
-
#initialize(scope, attribute_names, finder = :first, bang = false) ⇒ DynamicFinder
constructor
A new instance of DynamicFinder.
- #instantiator? ⇒ Boolean
Constructor Details
#initialize(scope, attribute_names, finder = :first, bang = false) ⇒ DynamicFinder
Returns a new instance of DynamicFinder.
3 4 5 |
# File 'lib/mongomodel/support/dynamic_finder.rb', line 3 def initialize(scope, attribute_names, finder=:first, bang=false) @scope, @attribute_names, @finder, @bang = scope, attribute_names, finder, bang end |
Class Method Details
.match(scope, method) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/mongomodel/support/dynamic_finder.rb', line 32 def self.match(scope, method) finder = :first bang = false case method.to_s when /^find_(all_by|last_by|by)_([_a-zA-Z]\w*)$/ finder = :last if $1 == 'last_by' finder = :all if $1 == 'all_by' names = $2 when /^find_by_([_a-zA-Z]\w*)\!$/ bang = true names = $1 when /^find_or_(initialize|create)_by_([_a-zA-Z]\w*)$/ finder = ($1 == 'initialize' ? :new : :create) names = $2 else return nil end names = names.split('_and_') if names.all? { |n| scope.klass.properties.include?(n.to_sym) } new(scope, names, finder, bang) end end |
Instance Method Details
#bang? ⇒ Boolean
24 25 26 |
# File 'lib/mongomodel/support/dynamic_finder.rb', line 24 def bang? @bang end |
#execute(*args) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/mongomodel/support/dynamic_finder.rb', line 7 def execute(*args) = args. conditions = build_conditions(args) result = @scope.where(conditions).send(instantiator? ? :first : @finder) if result.nil? if bang? raise DocumentNotFound, "Couldn't find #{@scope.klass.to_s} with #{conditions.inspect}" elsif instantiator? return @scope.send(@finder, conditions) end end result end |
#instantiator? ⇒ Boolean
28 29 30 |
# File 'lib/mongomodel/support/dynamic_finder.rb', line 28 def instantiator? @finder == :new || @finder == :create end |