How do you pass self to class_eval in ruby?

Posted by klochner on Stack Overflow See other posts from Stack Overflow or by klochner
Published on 2010-04-09T02:14:27Z Indexed on 2010/04/09 16:03 UTC
Read the original article Hit count: 150

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?

© Stack Overflow or respective owner

Related posts about metaprogramming

Related posts about ruby-on-rails