Skip to content

Commit

Permalink
Implemented find_by on association
Browse files Browse the repository at this point in the history
  • Loading branch information
Bantik committed Feb 25, 2013
1 parent cbe7e8a commit 343c5a3
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/faceted/has_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions lib/faceted/presenter.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
24 changes: 22 additions & 2 deletions spec/presenter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 343c5a3

Please sign in to comment.