0

我正在尝试从字符串实例化一个类,但是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
4

1 回答 1

3

尝试"SharingHelper::"在您之前添加到您的提供程序字符串:constantize。看起来您正在尝试查找顶级Twitter而不是SharingHelper::Twitter.

于 2013-06-06T19:14:43.310 回答