Skip to content

Commit

Permalink
Merge pull request #1 from albertlb/master
Browse files Browse the repository at this point in the history
Allow passing parameters to association "has many"
  • Loading branch information
pjb3 committed Mar 8, 2013
2 parents d558df8 + e8695a4 commit e0485f5
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 12 deletions.
29 changes: 17 additions & 12 deletions lib/attribution.rb
Expand Up @@ -195,20 +195,25 @@ def belongs_to(association_name, metadata={})

def has_many(association_name)
# foos
define_method(association_name) do
ivar = "@#{association_name}"
if instance_variable_defined?(ivar)
instance_variable_get(ivar)
else
# TODO: Support a more generic version of lazy-loading
begin
association_class = association_name.to_s.singularize.classify.constantize
rescue NameError => ex
raise ArgumentError.new("Association #{association_name} in #{self.class} is invalid because #{association_name.to_s.classify} does not exist")
define_method(association_name) do |*query|

# TODO: Support a more generic version of lazy-loading
begin
association_class = association_name.to_s.singularize.classify.constantize
rescue NameError => ex
raise ArgumentError.new("Association #{association_name} in #{self.class} is invalid because #{association_name.to_s.classify} does not exist")
end

if query.empty? # Ex: Books.all, so we want to cache it.
ivar = "@#{association_name}"
if instance_variable_defined?(ivar)
instance_variable_get(ivar)
elsif association_class.respond_to?(:all)
instance_variable_set(ivar, Array(association_class.all("#{self.class.name.underscore}_id" => id)))
end

else # Ex: Book.all(:name => "The..."), so we do not want to cache it
if association_class.respond_to?(:all)
instance_variable_set(ivar, Array(association_class.all("#{self.class.name.underscore}_id" => id)))
Array(association_class.all({"#{self.class.name.underscore}_id" => id}.merge(query.first)))
end
end
end
Expand Down
16 changes: 16 additions & 0 deletions test/attribution_test.rb
Expand Up @@ -28,6 +28,18 @@ class Book

belongs_to :book
has_many :chapters
has_many :readers
end

class Reader
include Attribution

integer :id

def self.all(query = {})
query
end

end

class Chapter
Expand Down Expand Up @@ -100,6 +112,10 @@ def test_create
assert_equal ActiveSupport::TimeZone["Eastern Time (US & Canada)"], book.time_zone
assert_equal 1, book.chapters.first.number
assert_equal 3, book.chapters.size
assert_equal ({}), Reader.all
assert_equal ([['book_id', 1]]), book.readers
assert_equal ([['book_id', 1], [:name,"julio"]]), book.readers(:name => 'julio')
assert_equal ([['book_id', 1]]), book.readers # Instance variable caching
assert_equal book, book.chapters.first.book
end

Expand Down

0 comments on commit e0485f5

Please sign in to comment.