I have not done much metaprogramming, but I thought I would try it on the latest project I’m working on. Actually this isn’t even metaprogramming, probably. I started by defining methods, but then realized I could just define has_one associations.
Basically we have users who can earn badges. (I know about the merit gem but we want to roll our own). Badge is an activerecord class that belongs_to User with all of the badge types subclassed. Single Table Inheritance. For example:
class SignedUpBadge < Badge
class PostedCommentBadge < Badge
So, I thought to generate a has_one association for each badge type. In the User class, if I do this:
[:signed_up_badge, :posted_comment_badge].each do |badgetype|
has_one badgetype
end
It works fine. But we plan on having probably up to fifty badge types, so I would rather just generate associations from a list of the Badge subclasses. When I do this:
Badge.descendants.each do |badgetype|
has_one badgetype.name.underscore.to_sym # not sure to_sym is even necessary
end
none of the associations are there. What am I missing?