From 72e3ac37d65b905d7d405d1fe8a32c799fdae07f Mon Sep 17 00:00:00 2001 From: Kim Burgestrand Date: Sun, 31 Jul 2011 04:40:31 +0200 Subject: [PATCH] Add CouchRest::Model::Base.respond_to_missing? and respond_to? --- lib/couchrest/model/base.rb | 15 +++++++++++++++ spec/unit/view_spec.rb | 17 ++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/couchrest/model/base.rb b/lib/couchrest/model/base.rb index ed46699..40cb968 100644 --- a/lib/couchrest/model/base.rb +++ b/lib/couchrest/model/base.rb @@ -82,6 +82,21 @@ module CouchRest super end + # compatbility for 1.8, it does not use respond_to_missing? + # thing is, when using it like this only, doing method(:find_by_view) + # will throw an error + def self.respond_to?(m, include_private = false) + super || respond_to_missing?(m, include_private) + end + + # ruby 1.9 feature + # this allows ruby to know that the method is defined using + # method_missing, and as such, method(:find_by_view) will actually + # give a Method back, and not throw an error like in 1.8! + def self.respond_to_missing?(m, include_private = false) + has_view?(m) || has_view?(m.to_s[/^find_(by_.+)/, 1]) + end + def to_key new? ? nil : [id] end diff --git a/spec/unit/view_spec.rb b/spec/unit/view_spec.rb index b58e037..d69630c 100644 --- a/spec/unit/view_spec.rb +++ b/spec/unit/view_spec.rb @@ -173,7 +173,22 @@ describe CouchRest::Model::Views do end end - + + describe "#method_missing for find_by methods" do + before(:all) { reset_test_db! } + + specify { Course.should respond_to :find_by_title_and_active } + specify { Course.should respond_to :by_title } + + specify "#method should work in ruby 1.9, but not 1.8" do + if RUBY_VERSION >= "1.9" + Course.method(:find_by_title_and_active).should be_a Method + else + expect { Course.method(:find_by_title_and_active) }.to raise_error(NameError) + end + end + end + describe "a ducktype view" do before(:all) do reset_test_db!