John Feminella
2012-Jan-18 18:20 UTC
Can you extend an association, but only for a specific instance?
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?
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Talk" group.
To post to this group, send email to
rubyonrails-talk-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
To unsubscribe from this group, send email to
rubyonrails-talk+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/Ez6ZCGd0@public.gmane.org
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en.