Class: BetterSeo::Generators::CanonicalUrlManager

Inherits:
Object
  • Object
show all
Defined in:
lib/better_seo/generators/canonical_url_manager.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url = nil) ⇒ CanonicalUrlManager

Returns a new instance of CanonicalUrlManager.



11
12
13
14
15
# File 'lib/better_seo/generators/canonical_url_manager.rb', line 11

def initialize(url = nil)
  @remove_query_params = false
  @lowercase = false
  self.url = url if url
end

Instance Attribute Details

#lowercaseObject

Returns the value of attribute lowercase.



9
10
11
# File 'lib/better_seo/generators/canonical_url_manager.rb', line 9

def lowercase
  @lowercase
end

#remove_query_paramsObject

Returns the value of attribute remove_query_params.



9
10
11
# File 'lib/better_seo/generators/canonical_url_manager.rb', line 9

def remove_query_params
  @remove_query_params
end

#urlObject

Returns the value of attribute url.



8
9
10
# File 'lib/better_seo/generators/canonical_url_manager.rb', line 8

def url
  @url
end

Instance Method Details

#to_htmlObject

Generate canonical link HTML tag



24
25
26
27
28
# File 'lib/better_seo/generators/canonical_url_manager.rb', line 24

def to_html
  return "" unless @url

  %(<link rel="canonical" href="#{escape_html(@url)}">)
end

#to_http_headerObject

Generate Link HTTP header



31
32
33
34
35
# File 'lib/better_seo/generators/canonical_url_manager.rb', line 31

def to_http_header
  return "" unless @url

  %(<#{@url}>; rel="canonical")
end

#validate!Object

Validate the canonical URL

Raises:



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/better_seo/generators/canonical_url_manager.rb', line 38

def validate!
  raise ValidationError, "URL is required" if @url.nil? || @url.empty?

  begin
    uri = URI.parse(@url)

    # Check if it's a relative URL
    raise ValidationError, "Canonical URL must be absolute: #{@url}" unless uri.absolute?

    # Check if it's HTTP or HTTPS
    raise ValidationError, "Invalid URL format: #{@url}" unless uri.is_a?(URI::HTTP) || uri.is_a?(URI::HTTPS)
  rescue URI::InvalidURIError
    raise ValidationError, "Invalid URL format: #{@url}"
  end

  true
end