如何从类的方法调用访问ActiveModel属性?

时间:2013-05-31 06:58:42

标签: ruby ruby-on-rails-3 activerecord

我需要引用user#role来定义模块中的关联。我已尝试使用如下所示的块,但这不起作用。 Rails如何实现这样的行为?

class User < ActiveRecord::Base
  include Profile
  has_profile { |user| { class_name: "#{user.role}::Profile" }}
end

module Profile
  extend ActiveSupport::Concern

  module ClassMethods

    def has_profile(&block)

      role = ### How to access #role ? ###

      class_eval do
        has_one :profile, class_name: "#{role}::Profile"
      end
      ...

2 个答案:

答案 0 :(得分:0)

你可能需要做这样的事情。我没有测试过,我只是假设你可以做这种事情

class User < ActiveRecord::Base
  include Profile
  has_profile { |user| user.role }
end

module Profile
  extend ActiveSupport::Concern

  included do  
    after_initialize :_init_profile
  end

  def _init_profile
    role = @_role_block.call(self)
    # Here we do class eval on singleton so we dont change base class
    # I'm not sure if this works as it is but should be close enought
    class << self; self; end.class_eval do
      has_one :profile, class_name: "#{role}::Profile"
    end
  end


  module ClassMethods

    def has_profile(&block)
      @_role_block = block
      ...

答案 1 :(得分:0)

这有效:

module Models
  module Profile
    extend ActiveSupport::Concern

    included do
      after_initialize :_init_profile
    end

    module ClassMethods
      def has_profile(&block)
        @profile_association_block = block
      end
    end

    def _init_profile
      block = self.class.instance_variable_get :@profile_association_block
      self.class.has_one :profile, block.call(self)
    end