Sha256: 0bc60de2c3e23c1d02d47ec8ac11b3e91cc2a4b4a4c553957d61f195fb0a7b67

Contents?: true

Size: 1.62 KB

Versions: 8

Compression:

Stored size: 1.62 KB

Contents

require 'social_parser/link'

module SocialParser

  class InvalidURIError < Exception; end

  module Provider
    class Base < ::SocialParser::Link

      def self.parse(attrs)
        if attrs[:provider]

          SocialParser::Provider.const_get(attrs[:provider].to_s.capitalize).new(attrs)
        else

          providers.map do |provider|
            SocialParser::Provider.const_get(provider.to_s.capitalize).new(attrs)
          end.find(&:valid?) or ::SocialParser::Link.new(attrs)
        end
      end

      def username
        return @username if @username
        if @url_or_username and invalid_url_format?(@url_or_username)
          @url_or_username
        elsif url_from_attributes
          parse_from_url
        end
      end

      def url
        return url_from_attributes if url_from_attributes
        "https://www.#{provider.to_s}.com/#{username}"
      end

      def domain
        'com'
      end

      def embed_url
        raise SocialParser::InvalidURIError
      end

      def valid?
        (@provider and @provider == provider) or
        (username and URI.parse(url_from_attributes).host.match("#{provider.to_s}.#{domain}"))
      rescue URI::BadURIError, URI::InvalidURIError
        false
      end

      alias_method :id, :username

      private

      def parse_from_url
        URI.parse(url_from_attributes).path.split('/')[1]
      rescue URI::BadURIError, URI::InvalidURIError
        nil
      end

      def self.providers
        @providers ||= [:facebook, :github, :twitter, :youtube, :instagram, :linkedin,
                        :medium, :qiita, :pinterest, :google, :vimeo]
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
social_parser-1.0.7 lib/social_parser/provider/base.rb
social_parser-1.0.6 lib/social_parser/provider/base.rb
social_parser-1.0.5 lib/social_parser/provider/base.rb
social_parser-1.0.4 lib/social_parser/provider/base.rb
social_parser-1.0.3 lib/social_parser/provider/base.rb
social_parser-1.0.2 lib/social_parser/provider/base.rb
social_parser-1.0.1 lib/social_parser/provider/base.rb
social_parser-1.0.0 lib/social_parser/provider/base.rb