Mohamad
Mohamad

Reputation: 35349

uninitialized constant error when instantiating class

I'm trying to instantiate a class from a string, but I keep getting an unitialized constant error Twitter whenever I call it, though: <%= share 'twitter', @post %>

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

I tried instantiating the class this way:

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

But that caused a 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

Upvotes: 0

Views: 1019

Answers (1)

Daniel J. Pritchett
Daniel J. Pritchett

Reputation: 1051

Try adding "SharingHelper::" to your provider string before you :constantize it. It looks like you're trying to find a top-level Twitter rather than SharingHelper::Twitter.

Upvotes: 3

Related Questions