RUBY:定义?(klass)看到局部变量而不是常量

我遇到了一个问题,我需要检查类是否存在。但是,我将类传递给变量,并尝试从那里进行检查。

我的问题是我需要传递实际的常量才能使 defined?()起作用,但是我传递的是变量,因此与其看到一个常量,不如看到一个方法或变量。

<html></html>是Rails模型实例,例如,特定的obj或特定的User

Car

试探输出:

  def present(obj,presenter_class=nil,view_context=nil)
    klass = presenter_class || "#{obj.class}Presenter".constantize
    if defined?(klass) == 'constant' && klass.class == Class 
      klass.new(obj,view_context)
    else
      warn("#{self}: #{klass} is not a defined class,no presenter used")
      obj
    end
  end

我尝试了以下方法,但是我找到了一种方法...

[1] pry(ApplicationPresenter)> defined?(klass) 
=> "local-variable"

如何解决此问题?

shz832003dky 回答:RUBY:定义?(klass)看到局部变量而不是常量

好吧,显然Object#defined?并不是您希望的。

  

测试表达式是否引用任何可识别的内容(文字对象,已初始化的局部变量,在当前作用域中可见的方法名称等)。如果无法解析表达式,则返回值为nil。否则,返回值将提供有关表达式的信息。

您的目标似乎就像是用.decorate来重建draper gem所做的一样...不要忘记,大多数gem都是开源的,您可以用它自己尝试。例如参见the decorator_class method from them

decorator_name = "#{prefix}Decorator"
decorator_name_constant = decorator_name.safe_constantize
return decorator_name_constant unless decorator_name_constant.nil?

他们使用方法safe_constantize,当常量不可用时,显然返回nil。

2.6.5 :007 > class UserPresenter; end;
 => nil 
2.6.5 :008 > 'UserPresenter'.safe_constantize
 => UserPresenter 
2.6.5 :009 > 'ForgottenPresenter'.safe_constantize
 => nil 

对我来说,它看起来完全像您的需求,safer than using constantize

  def present(obj,presenter_class=nil,view_context=nil)
    klass = presenter_class || "#{obj.class}Presenter".safe_constantize
    if klass != nil
      klass.new(obj,view_context)
    else
      warn("#{self}: #{klass} is not a defined class,no presenter used")
      obj
    end
  end
本文链接:https://www.f2er.com/2890127.html

大家都在问