我正在尝试从字符串中实例化一个类,但是每当我调用它时我都会收到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
答案 0 :(得分:3)
尝试在"SharingHelper::"
之前将:constantize
添加到您的提供商字符串中。您似乎正在尝试查找顶级Twitter
而不是SharingHelper::Twitter
。