【问题标题】:How to get the class name in ActiveSupport::Concern?如何在 ActiveSupport::Concern 中获取类名?
【发布时间】:2017-08-01 22:19:12
【问题描述】:

我有用户、产品和订单类。我有一个共同关注的 Logger,我已经将它包含在每个 Logger 中。我在 Logger 模块中有一个 after_create 回调,它将记录创建。我需要不同类型的类名和日志。

class User
  include Logger
  attr_accessor :name
end

class Product
  include Logger
  attr_accessor :name
end

class Order
  include Logger
  attr_accessor :name
end

我有记录器模块

module Logger
  extend ActiveSupport::Concern

  included do
    after_create :log_event
  end

  def log_event
    puts "#{<some way to get name of the class>} created now."
  end 
end

我想在那里“以某种方式获取班级名称”。我试过self.name(返回类的name属性中的值),self.class.name(返回类),self.downcase(返回错误),self.table_name(返回错误)。请让我知道这个问题的解决方案。我也不能过多地改变这个结构。

【问题讨论】:

  • 在使用 Logger 模块创建对象的上下文中,log_event 方法中puts self.inspect 的输出是什么?
  • 它给出了像 这样的 User 对象
  • 然后self 代表用户实例(在这种情况下)。 self.class 应该返回用户

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

在使用关注点时,您可以只使用self.name 而不是self.classself.class.name

例子:

def log_event
  puts "#{self.name} created now."
end 

【讨论】:

    【解决方案2】:

    与在普通实例方法中获取它的方式相同。

    def log_event
      puts "#{self.class} created now."
    end  
    

    你也可以self.class.name

    【讨论】:

    • 这给出了用户对象字符串
    • 如果您在User 上调用.class 而不是User 的对象,您将得到Class 作为输出
    • 您能否发布确切的方法和类定义(发布的没有AR继承)或在此方法中尝试prybyebugself 应该指向正在创建的用户对象
    • @PiKaY 这应该可以。如果你从self.class.table_name 得到users,那么self.class.name 应该是User。只是为了 100% 确定,我自己测试了你的模块。请发布更多你的类定义,一定有问题
    【解决方案3】:

    我想我找到了答案。我可以使用 self.class.table_name 来获取用户、产品等的名称,即如果表名不是自定义的

    【讨论】:

    • self.class.table_name 仅在 self.class 解析为 UserProduct 时才有效。 self.class.table_name 有效但 self.class 无效,这听起来不对。
    猜你喜欢
    • 2013-05-26
    • 2012-09-14
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 2013-02-01
    相关资源
    最近更新 更多