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