Permalink
Browse files

Person/Dog model updates

- Factor Model#matching_any into a module, use for people/dogs
- Add delegation for dog info accessed via litter
  • Loading branch information...
1 parent 90b9894 commit 0aeb6de081f10a2e1107a1deee2e0139c75f13ad @nickh committed Jun 14, 2011
Showing with 50 additions and 10 deletions.
  1. +4 −0 app/models/dog.rb
  2. +5 −10 app/models/person.rb
  3. +1 −0 config/initializers/any_matcher.rb
  4. +17 −0 lib/any_matcher.rb
  5. +19 −0 spec/models/dog_spec.rb
  6. +4 −0 spec/models/person_spec.rb
View
@@ -1,4 +1,6 @@
class Dog < ActiveRecord::Base
+ include AnyMatcher
+
belongs_to :owner, :class_name => 'Person'
belongs_to :litter
has_many :litters,
@@ -8,6 +10,8 @@ class Dog < ActiveRecord::Base
has_many :completed_certifications
has_many :diagnoses
+ delegate :breeder, :whelp_date, :to => :litter
+
def male?
!self.female?
end
View
@@ -1,17 +1,12 @@
class Person < ActiveRecord::Base
+ include AnyMatcher
+
has_many :dogs, :foreign_key => 'owner_id'
has_many :litters, :foreign_key => 'breeder_id'
has_many :club_memberships, :foreign_key => 'member_id'
has_many :clubs, :through => :club_memberships
- scope :matching_any, lambda {|conditions|
- match_string = '%%%s%%'
- table = unscoped.table
- column,val = conditions.shift
- base = table[column].matches(match_string % val)
- where(conditions.inject(base) do |where_clause, match|
- column,val = match
- where_clause.or(table[column].matches(match_string % val))
- end)
- }
+ def full_name
+ [first_name, last_name].join(' ')
+ end
end
@@ -0,0 +1 @@
+require 'any_matcher'
View
@@ -0,0 +1,17 @@
+module AnyMatcher
+ extend ActiveSupport::Concern
+
+ module ClassMethods
+ def matching_any(conditions)
+ match_string = '%%%s%%'
+ table = unscoped.table
+ filter_conditions = conditions.reject{|column, val| table[column].nil? || val.blank?}
+ column,val = filter_conditions.shift
+ base = table[column].matches(match_string % val)
+ where(filter_conditions.inject(base) do |where_clause, match|
+ column,val = match
+ where_clause.or(table[column].matches(match_string % val))
+ end)
+ end
+ end
+end
@@ -58,4 +58,23 @@
litter.dam.should == bitch
end
end
+
+ describe 'delegations to litter' do
+ before(:all) do
+ @litter = Factory.build(:litter)
+ @dog = Factory.build(:dog, :litter => @litter)
+ end
+
+ it 'delegates breeder' do
+ @dog.breeder.should == @litter.breeder
+ end
+
+ it 'delegates whelp_date' do
+ @dog.whelp_date.should == @litter.whelp_date
+ end
+ end
+
+ it 'matches any' do
+ Dog.should respond_to :matching_any
+ end
end
@@ -35,4 +35,8 @@
it 'has many clubs' do
subject.should have_many :clubs, :through => :club_memberships
end
+
+ it 'matches any' do
+ Person.should respond_to :matching_any
+ end
end

0 comments on commit 0aeb6de

Please sign in to comment.