Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Implemented find_by on association

  • Loading branch information...
commit 343c5a36e676b38e3dff469fe7aca60140d127c6 1 parent cbe7e8a
Bantik authored
View
2  lib/faceted/has_object.rb
@@ -75,7 +75,7 @@ def initialize_with_object
def object
return unless self.class.klass
- @object ||= self.id ? self.class.klass.find(self.id) : self.class.klass.new
+ @object ||= self.class.klass.where(find_by => self.send(find_by)) || self.class.klass.new
end
def object=(obj)
View
3  lib/faceted/presenter.rb
@@ -24,6 +24,9 @@ def klass
def presents(name, args={})
class_name = args[:class_name] || name.to_s.classify
@presents = eval(class_name)
+ define_method :find_by do
+ args[:find_by] || :id
+ end
define_method :"#{class_name.downcase}" do
object
end
View
24 spec/presenter_spec.rb
@@ -14,6 +14,13 @@ def attributes; {:id => self.id, :city => self.city, :state => self.state}; end
def reload; self; end
end
+class Album # and yet another make-believe AR model
+ attr_accessor :id, :name
+ def initialize(params={}); params.each{|k,v| self.send("#{k}=",v) if self.respond_to?(k)}; end
+ def attributes; {:id => self.id, :name => self.name}; end
+ def reload; self; end
+end
+
module MyApi
class Birthplace
@@ -32,15 +39,21 @@ class Musician
field :alive
end
+ class Album
+ include Faceted::Presenter
+ presents :album, :find_by => :name
+ field :name
+ end
+
describe Musician do
before do
@ar_musician = ::Musician.new(:id => 1, :name => 'Johnny Cash', :rating => 'Good', :alive => false)
- ::Musician.stub(:find) { @ar_musician }
+ ::Musician.stub(:where) { @ar_musician }
@ar_birthplace = ::Birthplace.new(:id => 1, :city => 'Kingsland', :state => 'Arkansas')
- ::Birthplace.stub(:find) { @ar_birthplace }
+ ::Birthplace.stub(:where) { @ar_birthplace }
end
@@ -110,6 +123,13 @@ class Musician
musician.birthplace.city.should == 'Kingsland'
end
+ it 'initializes the associated object finding by a specified key' do
+ @ar_album = ::Album.new(:id => 1, :name => 'Greatest Hits')
+ ::Album.stub(:where) { @ar_album }
+ album = MyApi::Album.new(:name => 'Greatest Hits')
+ album.id.should == 1
+ end
+
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.