ActiveRecord allows an association to be extended, as in:
module FindWeeklyExtension def weekly(start) where("created_at > :t1 and created_at < :t2", :t1 => start, :t2 => start + 7.days ) end end
class Author has_many :posts, :extend => FindWeeklyExtension end
Over time, though, classes might start to include many modules:
class Author # several modules
has_many :posts, :extend => [...] end
You might notice that you only need an extension or module to exist in one particular context:
module WeeklyDigest def weekly_posts(start) posts.weekly(start) end end
So it'd be cleaner not to have that in the class, and instead to do something like this:
# Author class Author has_many :posts # we refactored :extend => FindWeeklyExtension ... end
module WeeklyDigest def weekly_posts(start) posts.extend FindWeeklyExtension # ... and moved it here posts.weekly(start) end end
However, this doesn't work:
NoMethodError: undefined method `where' for #<Array: 0x00000007d0e970>
So, is there a good way to extend an association, but only for a specific instance's association?