Adding missing methods to proxy, proxy needs tests

This commit is contained in:
Sam Lown 2010-06-18 19:00:20 +02:00
parent 1b89f1e1df
commit 5580caf346
4 changed files with 29 additions and 6 deletions

View file

@ -140,8 +140,7 @@ module CouchRest
elsif m.to_s =~ /^find_(by_.+)/ elsif m.to_s =~ /^find_(by_.+)/
view_name = $1 view_name = $1
if has_view?(view_name) if has_view?(view_name)
query = {:key => args.first, :limit => 1} return find_first_from_view(view_name, *args)
return view(view_name, query).first
end end
end end
super super

View file

@ -47,10 +47,14 @@ module CouchRest
def method_missing(m, *args, &block) def method_missing(m, *args, &block)
if has_view?(m) if has_view?(m)
query = args.shift || {} query = args.shift || {}
view(m, query, *args, &block) return view(m, query, *args, &block)
else elsif m.to_s =~ /^find_(by_.+)/
super view_name = $1
if has_view?(view_name)
return find_first_from_view(view_name, *args)
end
end end
super
end end
# Mixins::DocumentQueries # Mixins::DocumentQueries
@ -76,6 +80,7 @@ module CouchRest
doc.database = @database if doc && doc.respond_to?(:database) doc.database = @database if doc && doc.respond_to?(:database)
doc doc
end end
alias :find :get
# Mixins::Views # Mixins::Views
@ -89,6 +94,12 @@ module CouchRest
docs docs
end end
def find_first_from_view(name, *args)
(args[1] ||= {})[:database] = @database
doc = @klass.find_first_from_view(name, args)
doc.database = @database if doc && doc.respond_to?(:database)
doc
end
# Mixins::DesignDoc # Mixins::DesignDoc

View file

@ -102,6 +102,18 @@ module CouchRest
fetch_view_with_docs(db, name, query, raw, &block) fetch_view_with_docs(db, name, query, raw, &block)
end end
# Find the first entry that matches the provided key.
# Request like:
#
# Course.find_first_from_view('teachers', 'Fred')
#
def find_first_from_view(name, *args)
key = args[0]
query = args[1] || {}
query.update(:limit => 1, :key => key)
view(name, query).first
end
private private
def fetch_view_with_docs(db, name, opts, raw=false, &block) def fetch_view_with_docs(db, name, opts, raw=false, &block)

View file

@ -126,7 +126,7 @@ describe "ExtendedDocument views" do
end end
end end
it "should return single matched record" do it "should return single matched record with find helper" do
course = Course.find_by_title('bbb') course = Course.find_by_title('bbb')
course.should_not be_nil course.should_not be_nil
course.title.should eql('bbb') # Ensure really is a Course! course.title.should eql('bbb') # Ensure really is a Course!
@ -151,6 +151,7 @@ describe "ExtendedDocument views" do
it "should raise exception if view not present" do it "should raise exception if view not present" do
lambda { Course.find_by_foobar('123') }.should raise_error(NoMethodError) lambda { Course.find_by_foobar('123') }.should raise_error(NoMethodError)
end end
end end
describe "a ducktype view" do describe "a ducktype view" do