How do you pass self to class_eval in ruby?
- by klochner
I'm working on a metaprogramming task, where I'm trying to use a single method to define a polymorphic association in the calling class, while also defining the association in the target class. I need to pass in the name of the calling class to get the association right. Here's a snippet that should get the idea across:
class SomeClass < ActiveRecord::Base
has_many :join_models, :dependent=:destroy
end
class JoinModel < ActiveRecord::Base
belongs_to :some_class
belongs_to :entity, :polymorphic=true
end
module Foo
module ClassMethods
def acts_as_entity
has_many :join_models, :as=:entity, :dependent=:destroy
has_many :some_classes, :through=:join_models
klass = self.name.tableize
SomeClass.class_eval "has_many :#{klass}, :through=:join_models"
end
end
end
I'd like to eliminate the klass= line, but don't know how else to pass a reference to self from the calling class into class_eval.
any suggestions?