【问题标题】:uninitialized constant error when instantiating class实例化类时出现未初始化的常量错误
【发布时间】:2023-03-20 11:45:01
【问题描述】:

我正在尝试从字符串中实例化一个类,但每当我调用它时,我都会收到 unitialized constant error Twitter,不过:<%= share 'twitter', @post %>

@provider = provider.classify.constantize.send(:new, post, link)

我尝试以这种方式实例化类:

"SharingHelper::Sharer::#{provider}".classify.constantize.send(:new, post, link)

但这导致了wrong constant name twitter

module SharingHelper
  def share(provider, post)
    Sharer.new(provider, post).generate
  end

  class Sharer
    def initialize(provider, post)
      @provider = provider.classify.constantize.send(:new, post)
    end

    def generate
      link_to @provider.class.name, @provider.url
    end
  end

  class BaseProvider
    include ActionView::Helpers::UrlHelper
    include ActionView::Helpers::TextHelper

    def initialize(post)
      @post = post
    end

    def url
      ADDRESS + post_data
    end
  end

  class Facebook < BaseProvider
    ADDRESS  = 'http://www.facebook.com/sharer.php?s=100&'

    private    
    def post_data
      # do stuff
    end
  end

  class Twitter < BaseProvider
    ADDRESS  = 'https://twitter.com/share?'

    private    
    def post_data
      # do stuff
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    尝试在:constantize 之前将"SharingHelper::" 添加到您的提供程序字符串中。您似乎正在尝试查找顶级 Twitter 而不是 SharingHelper::Twitter

    【讨论】:

    • 如果我理解正确的话,我确实尝试过,但我得到了一个wrong constant name twitter"SharingHelper::Sharer::#{provider}".classify.constantize.send(:new, post)
    • 我也尝试了@provider = "SharingHelper::#{provider}".constantize.send(:new, post) 并得到了同样的错误wrong constant name twitter
    • 您需要强制它大写 Twitter。您的分类和常量化方法不够聪明,无法知道 :titleize 那个词。
    猜你喜欢
    • 2017-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 2012-10-10
    相关资源
    最近更新 更多