### Install Gems with Bundler Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/11-setup-guide.md Run 'bundle install' to install the meta-tags gem and its dependencies. ```bash bundle install ``` -------------------------------- ### Setup Development Environment Source: https://github.com/kpumuk/meta-tags/blob/main/CONTRIBUTING.md Run the setup script to configure your local development environment for the Meta Tags project. This script prepares the necessary dependencies and configurations. ```bash ./bin/setup ``` -------------------------------- ### display_meta_tags Examples Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Examples demonstrating the usage of the `display_meta_tags` method with various options. ```APIDOC ## display_meta_tags Examples ### Description Examples demonstrating the usage of the `display_meta_tags` method with various options. ### Request Example ```erb <%= display_meta_tags separator: "—".html_safe %> <%= display_meta_tags prefix: false, separator: ":" %> <%= display_meta_tags lowercase: true %> <%= display_meta_tags reverse: true, prefix: false %> <%= display_meta_tags og: { title: "The Rock", type: "video.movie" } %> <%= display_meta_tags alternate: { "zh-Hant" => "http://example.com.tw/base/url" } %> ``` ``` -------------------------------- ### set_meta_tags Examples Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Examples demonstrating how to set meta tags using the `set_meta_tags` method, including handling arrays for titles and legacy keywords. ```APIDOC ## set_meta_tags Examples ### Description Examples demonstrating how to set meta tags using the `set_meta_tags` method, including handling arrays for titles and legacy keywords. ### Request Example ```ruby set_meta_tags title: ["part1", "part2"], site: "site" # Expected output: site | part1 | part2 set_meta_tags title: ["part1", "part2"], reverse: true, site: "site" # Expected output: part2 | part1 | site set_meta_tags keywords: ["tag1", "tag2"] # Expected output: tag1, tag2 ``` ``` -------------------------------- ### Usage Examples Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Examples demonstrating how to create and render various types of meta tags using the MetaTags library. ```APIDOC ### Creating Meta Tags ```ruby # Meta tag with attributes meta_tag = MetaTags::Tag.new(:meta, name: "description", content: "My page") # Link tag for canonical link_tag = MetaTags::Tag.new(:link, rel: "canonical", href: "https://example.com") # Title tag with content title_tag = MetaTags::ContentTag.new(:title, content: "My Page Title") # With custom attributes title_tag = MetaTags::ContentTag.new(:title, content: "My Page Title", id: "page-title", class: "header-title" ) ``` ### Rendering Multiple Tags ```ruby view = ActionView::Base.new(ActionView::LookupContext.new([])) tags = [ MetaTags::ContentTag.new(:title, content: "Home"), MetaTags::Tag.new(:meta, name: "description", content: "Welcome"), MetaTags::Tag.new(:link, rel: "canonical", href: "https://example.com") ] html = tags.map { |tag| tag.render(view) }.join("\n") ``` ### DateTime Serialization ```ruby published_time = Time.parse("2024-01-15T10:30:00Z") tag = MetaTags::Tag.new(:meta, property: "article:published_time", content: published_time ) # The datetime is automatically serialized to ISO 8601 format html = tag.render(view) # => '' ``` ### Rendering Configuration The renderer respects the `MetaTags.config.open_meta_tags?` setting: ```ruby # With open_meta_tags = true (default) MetaTags.config.open_meta_tags = true tag = MetaTags::Tag.new(:meta, name: "viewport", content: "width=device-width") html = tag.render(view) # => '' # With open_meta_tags = false (XHTML style) MetaTags.config.open_meta_tags = false html = tag.render(view) # => '' ``` ``` -------------------------------- ### Complete Meta Tags Example Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/08-types.md A comprehensive example demonstrating the use of various meta tag types including control, basic, SEO, Open Graph, Twitter, and link formats. ```ruby set_meta_tags( # Control site: "My Site", separator: " | ", # Basic title: "Article Title", description: "Article description", keywords: %w[tag1 tag2 tag3], # SEO canonical: "https://example.com/article/1", noindex: false, robots: { "max-snippet" => -1 }, # Open Graph og: { title: :title, description: :description, type: "article", url: "https://example.com/article/1", image: { _: "https://example.com/image.jpg", width: 1200, height: 630, type: "image/jpeg" }, published_time: Time.current.iso8601, author: "John Doe" }, # Twitter twitter: { card: "summary_large_image", site: "@mysite", creator: "@author", image: "https://example.com/image.jpg" }, # Links prev: "https://example.com/article/0", next: "https://example.com/article/2", alternate: { "fr" => "https://example.fr/article/1" } ) ``` -------------------------------- ### Set MetaTags Configuration Options Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/10-module-api.md Example of setting various configuration options for MetaTags within a `configure` block. This is typically done in an initializer file. ```ruby MetaTags.configure do |config| config.title_limit = 100 config.description_limit = 160 config.minify_output = true config.skip_canonical_links_on_noindex = true end ``` -------------------------------- ### Example: Render ContentTag with Attributes Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Demonstrates rendering a ContentTag with additional HTML attributes, such as an ID. The output is an HTML string. ```ruby tag = MetaTags::ContentTag.new(:title, content: "Page Title", id: "page-title") html = tag.render(view) # => 'Page Title' ``` -------------------------------- ### Typical MetaTags Configuration in Initializer Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/10-module-api.md A comprehensive example of configuring MetaTags in a Rails initializer, setting multiple options for title, description, keywords, and output. ```ruby # config/initializers/meta_tags.rb MetaTags.configure do |config| config.title_limit = 70 config.title_tag_attributes = { id: "page-title" } config.description_limit = 300 config.keywords_limit = 255 config.keywords_separator = ", " config.keywords_lowercase = true config.open_meta_tags = true config.minify_output = false config.skip_canonical_links_on_noindex = false end ``` -------------------------------- ### Create Various Meta Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Examples of creating different types of meta tags, including standard meta tags, link tags for canonical URLs, and title tags with content. ```ruby # Meta tag with attributes meta_tag = MetaTags::Tag.new(:meta, name: "description", content: "My page") # Link tag for canonical link_tag = MetaTags::Tag.new(:link, rel: "canonical", href: "https://example.com") # Title tag with content title_tag = MetaTags::ContentTag.new(:title, content: "My Page Title") # With custom attributes title_tag = MetaTags::ContentTag.new(:title, content: "My Page Title", id: "page-title", class: "header-title" ) ``` -------------------------------- ### Example: Setting Meta Tags and Rendering Article Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/02-controller-helper.md Demonstrates how to find an article, set the page title and description using instance variables, and then render the associated view. The `render :show` call will trigger the `render` method in `ControllerHelper` to process these meta tags. ```ruby class ArticleController < ApplicationController def show @article = Article.find(params[:id]) @page_title = "Article: #{@article.title}" @page_description = @article.summary render :show end end ``` -------------------------------- ### Example Normalized Meta Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/05-renderer.md Illustrates the content of `normalized_meta_tags` after rendering, showing resolved title values. ```ruby # After rendering, contains resolved values renderer.normalized_meta_tags[:title] # => "Home" renderer.normalized_meta_tags[:full_title] # => "My Site | Home" renderer.normalized_meta_tags[:description] # => "Welcome to my site" ``` -------------------------------- ### Access and Modify Configuration Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/10-module-api.md Demonstrates how to get, set, and configure multiple values for the MetaTags module. Use these patterns to customize the behavior of meta tag generation. ```ruby # Get a configuration value limit = MetaTags.config.title_limit # Set a configuration value MetaTags.config.title_limit = 100 # Configure multiple values at once MetaTags.configure do |config| config.title_limit = 100 config.description_limit = 160 end # Access configuration during runtime if MetaTags.config.minify_output? # Handle minified output end ``` -------------------------------- ### Controller Helper Example Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/09-railtie.md Demonstrates how MetaTags::ControllerHelper methods are automatically available in Rails controllers. Use `@page_title`, `@page_description`, and `#set_meta_tags` to manage meta information. ```ruby class PostsController < ApplicationController def show @post = Post.find(params[:id]) @page_title = @post.title # Automatically processed @page_description = @post.excerpt # Automatically processed render :show end def index set_meta_tags(noindex: true) # Available from ControllerHelper render :index end end ``` -------------------------------- ### HTML Meta Tag Example Source: https://github.com/kpumuk/meta-tags/blob/main/CONTRIBUTING.md This is a standard HTML meta tag example using the 'name' attribute. It is used for general metadata like keywords. ```html ``` -------------------------------- ### Example: Setting Specific Meta Tags for Login Page Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/02-controller-helper.md Shows how to use `set_meta_tags` within a controller action to define the title, description, and a specific directive like `noindex` for the login page. This method merges these tags with any pre-existing ones. ```ruby class LoginController < ApplicationController def index set_meta_tags( title: 'Member Login', description: 'Member login page.', noindex: true ) end end ``` -------------------------------- ### View Helper Example Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/09-railtie.md Illustrates the usage of MetaTags::ViewHelper methods within Rails views and view helpers. Methods like `#display_meta_tags`, `#title`, and `#description` can be used to set and render meta tags. ```erb <%= display_meta_tags site: 'My Site' %>

<%= title @post.title %>

<% description @post.excerpt %> <% noindex if @post.draft? %> ``` -------------------------------- ### Set Description Meta Tag Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Set the description meta tag for search engine snippets. This example shows how to set a basic description. ```ruby set_meta_tags description: "This is a sample description" # ``` -------------------------------- ### Get Global MetaTags Configuration Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/10-module-api.md Accesses the global configuration singleton for MetaTags. Use this to read current configuration values. ```ruby def self.config @config ||= Configuration.new end ``` -------------------------------- ### Pagination Links for Previous and Next Pages Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/12-common-patterns.md Implement pagination links to guide users and search engines between paginated content. Ensure the previous page link is only set if the current page is greater than one. The next page link is set if a next page exists. ```ruby def index page = params[:page] || 1 @articles = Article.page(page).per(20) if page.to_i > 1 set_meta_tags prev: articles_path(page: page.to_i - 1) end if @articles.next_page set_meta_tags next: articles_path(page: @articles.next_page) end end ``` ```html ``` -------------------------------- ### Set and Get Page Title Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/01-view-helper.md Sets the page title and returns it, or returns a specified headline. If title is nil, it returns the current page title. ```ruby def title(title = nil, headline = "") set_meta_tags(title: title) unless title.nil? headline.presence || meta_tags.page_title end ``` -------------------------------- ### Configure Meta Tags Gem Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/README.md Customize the behavior of the meta-tags gem by using the `MetaTags.configure` block. This example sets the maximum length for the title tag. ```ruby MetaTags.configure do |config| config.title_limit = 70 end ``` -------------------------------- ### Initialize Configuration Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/04-configuration.md Initializes a new Configuration instance with default values. This can be done directly or by accessing the global configuration instance. ```ruby def initialize reset_defaults! end ``` ```ruby config = MetaTags::Configuration.new # Or access the global configuration config = MetaTags.config ``` -------------------------------- ### Get Current Page Title Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/01-view-helper.md Retrieves the current page title. ```erb <%= title %> ``` -------------------------------- ### Get MetaTags::Tag Attributes Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Retrieves the hash of HTML attributes associated with a Tag instance. ```ruby attr_reader :attributes ``` ```ruby tag = MetaTags::Tag.new(:meta, name: "keywords", content: "tag1, tag2") tag.attributes # => {name: "keywords", content: "tag1, tag2"} ``` -------------------------------- ### Read MetaTags Configuration Values Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/10-module-api.md Demonstrates how to access specific configuration settings like title and description limits using the `config` method. ```ruby MetaTags.config.title_limit # => 70 MetaTags.config.description_limit # => 300 ``` -------------------------------- ### Get MetaTags::Tag Name Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Retrieves the HTML tag name (e.g., 'meta', 'link') from a Tag instance. ```ruby attr_reader :name ``` ```ruby tag = MetaTags::Tag.new(:meta) tag.name # => "meta" ``` -------------------------------- ### MetaTags::Configuration#initialize Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/04-configuration.md Initializes a new Configuration instance with default values. This is the primary way to create a configuration object, or you can access the global configuration via `MetaTags.config`. ```APIDOC ## initialize() ### Description Initializes a new Configuration instance with default values. ### Method `initialize` ### Example ```ruby config = MetaTags::Configuration.new # Or access the global configuration config = MetaTags.config ``` ``` -------------------------------- ### Update Titles in Turbo Responses Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/11-setup-guide.md Use turbo-stream to update the page title and content in Turbo responses. This example shows how to target the 'page-title' element. ```erb ``` -------------------------------- ### Configuration Methods Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/INDEX.md Methods for global configuration of the Meta Tags module. ```APIDOC ## MetaTags.config ### Description Access global config. ### Purpose Provides access to the global configuration object for the Meta Tags module. ### Method Signature `MetaTags.config` ``` ```APIDOC ## MetaTags.configure ### Description Configure globally. ### Purpose Allows setting global configuration options for the Meta Tags module. ### Method Signature `MetaTags.configure do |config| ... end` ``` -------------------------------- ### Default Meta-Tags Configuration Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/11-setup-guide.md Customize limits, title formatting, output, and keyword options in the initializer. ```ruby MetaTags.configure do |config| # Limits and truncation config.title_limit = 70 config.description_limit = 300 config.keywords_limit = 255 # Title formatting config.truncate_site_title_first = false config.truncate_on_natural_separator = " " config.truncate_array_items_at_boundaries = false # Output formatting config.open_meta_tags = true config.minify_output = false # Title tag HTML attributes config.title_tag_attributes = {} # Keyword options config.keywords_separator = ", " config.keywords_lowercase = true # SEO options config.skip_canonical_links_on_noindex = false end ``` -------------------------------- ### Define Default Meta Tags Helper Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/11-setup-guide.md Create a helper method in `ApplicationHelper` to define consistent default meta tags, including site name and separator. This promotes uniformity across your site. ```ruby # app/helpers/application_helper.rb module ApplicationHelper def default_meta_tags { site: "My Awesome Site", separator: " • ", og: { site_name: "My Awesome Site" } } end end ``` -------------------------------- ### Combine Instance Variables and `set_meta_tags` Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/02-controller-helper.md You can combine setting instance variables for basic tags with the `set_meta_tags` method for more advanced options like `nofollow`. This approach is useful when you need both simple and complex meta tag configurations. ```ruby class ArticleController < ApplicationController def show @article = Article.find(params[:id]) @page_title = "#{@article.title} - Articles" @page_description = @article.summary set_meta_tags( canonical: article_url(@article), nofollow: true # If on internal pages ) end end ``` -------------------------------- ### Display Meta Tags with Prefix and Separator Options Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Customize meta tags by disabling the prefix and setting a specific separator. This example uses a colon as the separator. ```erb <%= display_meta_tags prefix: false, separator: ":" %> ``` -------------------------------- ### Set Simple Meta Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/README.md Use `set_meta_tags` to define basic meta tags like title and description. These will be rendered in the HTML head. ```ruby set_meta_tags( title: "Home", description: "Welcome" ) ``` -------------------------------- ### initialize Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/03-meta-tags-collection.md Initializes a new instance of MetaTagsCollection with an empty HashWithIndifferentAccess. ```APIDOC ## initialize ### Description Initializes a new instance of MetaTagsCollection with an empty HashWithIndifferentAccess. ### Method `initialize` ### Parameters None ### Returns `MetaTagsCollection` - A new instance of the collection. ### Example ```ruby tags = MetaTags::MetaTagsCollection.new ``` ``` -------------------------------- ### Access Meta Tags Gem Version Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/10-module-api.md Retrieve the currently installed version of the Meta Tags gem by requiring the version file and accessing the `MetaTags::VERSION` constant. ```ruby require "meta_tags/version" MetaTags::VERSION # => "2.20.0" (or current version) ``` -------------------------------- ### Simple String Meta Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/08-types.md Use simple string keys for basic meta tags like title, description, keywords, author, and viewport. These render with the 'name' attribute. ```ruby { title: "Page Title", description: "Page description", keywords: "keyword1, keyword2", author: "John Doe", viewport: "width=device-width, initial-scale=1.0" } ``` ```html Page Title ``` -------------------------------- ### Get Meta Tag Value Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/03-meta-tags-collection.md Retrieves a meta tag's value using its name. Supports both string and symbol keys. Returns nil if the tag is not set. ```ruby def [](name) @meta_tags[name] end ``` ```ruby tags = MetaTagsCollection.new tags[:title] = "Home" tags[:title] # => "Home" tags['title'] # => "Home" ``` -------------------------------- ### RSpec Test for Page Title Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/11-setup-guide.md Verify that the page title is correctly set in the response body during a GET request for an article. This test ensures the basic title tag is present. ```ruby # spec/requests/articles_spec.rb describe ArticlesController do describe "GET show" do let(:article) { create(:article) } subject { get article_path(article) } it "sets the page title" subject expect(response.body).to include("#{article.title}") end end end ``` -------------------------------- ### Set Meta Tags with Keywords Array Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Provide keywords for the legacy `keywords` meta tag as an array. The output will be a comma-separated string. ```ruby set_meta_tags keywords: ["tag1", "tag2"] # tag1, tag2 ``` -------------------------------- ### Extract Robots Directives Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/03-meta-tags-collection.md Extracts noindex and follow settings from meta tags. Use this method to get a hash of robot directives for different bots like 'robots', 'googlebot', and 'bingbot'. ```ruby def extract_robots result = Hash.new { |h, k| h[k] = [] } [ [:noindex, :index], [:follow, :nofollow], :noarchive ].each do |attributes| calculate_robots_attributes(result, attributes) end [:robots, :googlebot, :bingbot].each do |bot| values = extract(bot).presence if values result[bot.to_s].concat(values.map { |k, v| "#{k}:#{v}" }) end end result.transform_values { |v| v.join(", ") } end ``` ```ruby tags = MetaTagsCollection.new tags.update( noindex: true, nofollow: 'googlebot', robots: { "max-snippet" => -1 } ) robots = tags.extract_robots # => { # "robots" => "noindex, max-snippet:-1", # "googlebot" => "nofollow" # } ``` -------------------------------- ### Instantiate ContentTag Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Create a new ContentTag instance for HTML tags that contain text content. Specify the tag name and provide content via the 'content' option. ```ruby tag = MetaTags::ContentTag.new(:title, content: "Page Title") ``` -------------------------------- ### Get Default Property Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/04-configuration.md Retrieves the default meta tag prefixes and names that use the `property` attribute instead of `name`. These are commonly used for social media and structured data. ```ruby def default_property_tags [ "al", # App Links "fb", # Facebook "og", # Open Graph "article", # Article object "book", # Book object "books", # Books object "business", # Business object "fitness", # Fitness object "game", # Game object "music", # Music object "place", # Place object "product", # Product object "profile", # Profile object "restaurant", # Restaurant object "video" # Video object ].freeze end ``` ```ruby MetaTags.config.default_property_tags # => ["al", "fb", "og", "article", "book", ..., "video"] ``` -------------------------------- ### Initialize MetaTags::Tag Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Initializes a new instance of the Tag class. Use this to create tag objects with a name and optional attributes. ```ruby def initialize(name, attributes = {}) @name = name.to_s @attributes = attributes end ``` ```ruby tag = MetaTags::Tag.new(:meta, name: "description", content: "Welcome") tag = MetaTags::Tag.new(:link, rel: "canonical", href: "https://example.com") ``` -------------------------------- ### Configure Meta Tags Gem Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/README.md Customize global settings for the meta-tags gem, such as title and description length limits. This configuration should be done once, typically at application startup. ```ruby MetaTags.configure do |config| config.title_limit = 70 config.description_limit = 300 end ``` -------------------------------- ### Example: Directly Setting Page Title via Meta Tags Collection Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/02-controller-helper.md Illustrates how to directly set the page title by accessing and updating the `meta_tags` collection within a controller action. This approach is an alternative to using the `@page_title` instance variable. ```ruby class ArticleController < ApplicationController def show @article = Article.find(params[:id]) meta_tags[:title] = "Article: #{@article.title}" end end ``` -------------------------------- ### Renderer Constructor Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/05-renderer.md Initializes a new instance of the Renderer class with a MetaTagsCollection. ```APIDOC ## initialize(meta_tags) ### Description Initializes a new instance of Renderer with a meta tags collection to render. ### Parameters #### Path Parameters - **meta_tags** (MetaTagsCollection) - Required - Meta tags collection to render. ### Request Example ```ruby tags = MetaTagsCollection.new tags.update(title: "Home", description: "Welcome") renderer = Renderer.new(tags) ``` ``` -------------------------------- ### Set Meta Tags with Array Title and Site Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Configure meta tags with a multi-part title provided as an array, alongside the site name. The output format depends on the `reverse` option. ```ruby set_meta_tags title: ["part1", "part2"], site: "site" # site | part1 | part2 ``` ```ruby set_meta_tags title: ["part1", "part2"], reverse: true, site: "site" # part2 | part1 | site ``` -------------------------------- ### Extract Title Separator - Ruby Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/03-meta-tags-collection.md Extracts the title separator, including prefix and suffix, and then deletes these related meta tags. Handles cases where the separator is explicitly set to false. Use this to get the formatted string that joins title parts. ```ruby def extract_separator if meta_tags[:separator] == false prefix = separator = suffix = "" else prefix = extract_separator_section(:prefix, " ") separator = extract_separator_section(:separator, "|") suffix = extract_separator_section(:suffix, " ") end delete(:separator, :prefix, :suffix) TextNormalizer.safe_join([prefix, separator, suffix], "") end ``` ```ruby tags = MetaTagsCollection.new tags.update(prefix: " ", separator: "|", suffix: " ") separator = tags.extract_separator # => " | " ``` -------------------------------- ### Get Configured Meta Tag Name Key Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/05-renderer.md Determines the correct attribute name (`:property` or `:name`) for a meta tag based on the `MetaTags.config.property_tags` configuration. This is used to differentiate between standard meta tags and property-based tags like Open Graph. ```ruby def configured_name_key(name) name = name.to_s is_property_tag = MetaTags.config.property_tags.any? do |tag_name| property_tag?(name, tag_name.to_s) end is_property_tag ? :property : :name end ``` -------------------------------- ### Icon Link String Format Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/08-types.md The simplest format for icon links, specifying only the path to the favicon. ```ruby { icon: "/favicon.ico" } ``` -------------------------------- ### Performance-Focused Meta-Tags Configuration Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/11-setup-guide.md Enable output minification and use natural separators for faster rendering on high-traffic sites. ```ruby MetaTags.configure do |config| # Minify HTML output config.minify_output = true # Shorter processing with natural separators config.truncate_on_natural_separator = /\s+/ end ``` -------------------------------- ### Construct Page Title - Ruby Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/03-meta-tags-collection.md Constructs the page title, excluding the site title. Returns the site title if the page title is empty. Use when you need to get the display title for a page, potentially falling back to the site's name. ```ruby def page_title(defaults = {}) had_site = @meta_tags.key?(:site) old_site = @meta_tags[:site] @meta_tags[:site] = nil if had_site full_title = with_defaults(defaults) { extract_full_title } full_title.presence || old_site || "" ensure @meta_tags[:site] = old_site if had_site end ``` ```ruby tags = MetaTagsCollection.new tags.update( site: "My Site", title: "Home Page" ) tags.page_title # => "Home Page" tags[:title] = nil tags.page_title # => "My Site" ``` -------------------------------- ### Run Project Tests Source: https://github.com/kpumuk/meta-tags/blob/main/CONTRIBUTING.md Execute the 'rake' command to run the project's test suite. This ensures that your changes have not introduced any regressions and that the project remains stable. ```bash rake ``` -------------------------------- ### Article Model Implementation of to_meta_tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/08-types.md An example of how to implement the `to_meta_tags` method in a Rails model to generate a comprehensive set of meta tags, including title, description, canonical URL, Open Graph tags, and Twitter card tags. This implementation is used with `set_meta_tags`. ```ruby class Article < ApplicationRecord def to_meta_tags { title: self.title, description: self.excerpt, canonical: Rails.application.routes.url_helpers.article_url(self, only_path: false), og: { title: self.title, description: self.excerpt, image: self.featured_image_url, type: 'article', published_time: self.published_at&.iso8601, modified_time: self.updated_at.iso8601 }, twitter: { card: 'summary_large_image', image: self.featured_image_url } } end end # Usage article = Article.find(1) set_meta_tags(article) # Calls to_meta_tags internally ``` -------------------------------- ### Basic SEO Meta Tags in Ruby Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/12-common-patterns.md Implement core SEO meta tags for title, description, canonical URL, and robots directives. Ensure the `set_meta_tags` helper is available in your controller. ```ruby class ArticlesController < ApplicationController def show @article = Article.find(params[:id]) set_meta_tags( title: @article.title, description: @article.excerpt, canonical: article_url(@article), robots: { "max-snippet" => -1 } ) end end ``` -------------------------------- ### Construct Full Title Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/03-meta-tags-collection.md Generates the complete title string, including site name and separators, by applying defaults and extracting the full title. The defaults are temporary. ```ruby def full_title(defaults = {}) with_defaults(defaults) { extract_full_title } end ``` ```ruby tags = MetaTagsCollection.new tags.update( site: "My Site", title: "Home Page", separator: " | " ) tags.full_title # => "My Site | Home Page" ``` -------------------------------- ### Initialize Renderer Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/05-renderer.md Initializes a new Renderer instance with a MetaTagsCollection. This sets up the object to process and render the provided tags. ```ruby def initialize(meta_tags) @meta_tags = meta_tags @normalized_meta_tags = {} end ``` ```ruby tags = MetaTagsCollection.new tags.update(title: "Home", description: "Welcome") renderer = Renderer.new(tags) ``` -------------------------------- ### Configure Open Meta Tag Rendering Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Shows how to configure the rendering of meta tags between standard HTML5 and XHTML style self-closing tags using the `MetaTags.config.open_meta_tags` setting. ```ruby # With open_meta_tags = true (default) MetaTags.config.open_meta_tags = true tag = MetaTags::Tag.new(:meta, name: "viewport", content: "width=device-width") html = tag.render(view) # => '' # With open_meta_tags = false (XHTML style) MetaTags.config.open_meta_tags = false html = tag.render(view) # => '' ``` -------------------------------- ### Clone Meta Tags Repository Source: https://github.com/kpumuk/meta-tags/blob/main/CONTRIBUTING.md Clone the Meta Tags repository to your local machine to begin development. Ensure you replace 'your-username' with your actual GitHub username. ```bash git clone git@github.com:your-username/meta-tags.git ``` -------------------------------- ### render(*args, &block) Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/02-controller-helper.md Processes the @page_title, @page_description, and @page_keywords instance variables and calls the standard Rails render method. ```APIDOC ## render(*args, &block) ### Description Processes the `@page_title`, `@page_description`, and `@page_keywords` instance variables and calls the standard Rails `render` method. ### Method `render` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby class ArticleController < ApplicationController def show @article = Article.find(params[:id]) @page_title = "Article: #{@article.title}" @page_description = @article.summary render :show end end ``` ### Response #### Success Response (200) Returns the result of the render block. #### Response Example None explicitly defined, relies on Rails render behavior. ``` -------------------------------- ### Configure Open vs. Closed Meta Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/04-configuration.md Switch between rendering open (``) and closed (``) meta tags. Defaults to true (open). ```ruby MetaTags.configure do |config| config.open_meta_tags = true # end ``` -------------------------------- ### Open Search Format Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/08-types.md Configure Open Search by providing a `title` and the `href` to the Open Search description document. ```ruby { open_search: { title: "My Search", href: "/opensearch.xml" } } ``` -------------------------------- ### Set Manifest Link Meta Tag Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Specify the location of the web app manifest file using rel="manifest". This enables features like offline access and home screen adding. ```ruby set_meta_tags manifest: "manifest.json" # ``` -------------------------------- ### Set Keywords Meta Tag Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Use the `keywords` tag for legacy systems. Note that search engines like Google and Bing ignore this tag for SEO purposes. ```ruby set_meta_tags keywords: %w[keyword1 keyword2 keyword3] # ``` -------------------------------- ### Set Open Search Meta Tag Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Configure Open Search meta tags using `set_meta_tags` with the `open_search` option. This requires a title and the path to the search description XML file. ```ruby set_meta_tags open_search: { title: "Open Search", href: "/opensearch.xml" } # ``` -------------------------------- ### Set Meta Tags Using Instance Variables Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/02-controller-helper.md Assign meta tag content to instance variables like `@page_title` and `@page_description` in your controller actions. This is a common pattern for simpler meta tag management. ```ruby class PostsController < ApplicationController def show @post = Post.find(params[:id]) @page_title = @post.title @page_description = @post.excerpt end end ``` -------------------------------- ### Multi-Regional Content with Alternate Links Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/12-common-patterns.md Implement multi-language and multi-region support by defining alternate links for different locales. The 'x-default' key specifies the fallback URL for unsupported languages. ```ruby def show @article = Article.find(params[:id]) set_meta_tags( title: @article.title, description: @article.excerpt, alternate: { 'fr' => article_url(@article, locale: 'fr'), 'de' => article_url(@article, locale: 'de'), 'es' => article_url(@article, locale: 'es'), 'x-default' => article_url(@article, locale: 'en') } ) end ``` ```html ``` -------------------------------- ### Set Meta Tags in Controller Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Define instance variables in your controller to set the page title and description. ```ruby @page_title = "Member Login" @page_description = "Member login page." ``` -------------------------------- ### Render Multiple Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Renders an array of different meta tags, joining their HTML output with newline characters. Requires an ActionView::Base instance for rendering. ```ruby view = ActionView::Base.new(ActionView::LookupContext.new([])) tags = [ MetaTags::ContentTag.new(:title, content: "Home"), MetaTags::Tag.new(:meta, name: "description", content: "Welcome"), MetaTags::Tag.new(:link, rel: "canonical", href: "https://example.com") ] html = tags.map { |tag| tag.render(view) }.join("\n") ``` -------------------------------- ### Railtie Initialization for Meta Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/09-railtie.md This Railtie sets up the integration of MetaTags helpers into Rails controllers and views. It uses ActiveSupport.on_load to include the necessary modules when ActionController and ActionView are loaded. ```ruby class Railtie < Rails::Railtie initializer "meta_tags.setup_action_controller" do ActiveSupport.on_load :action_controller do include MetaTags::ControllerHelper end end initializer "meta_tags.setup_action_view" do ActiveSupport.on_load :action_view do include MetaTags::ViewHelper end end end ``` -------------------------------- ### Generate MetaTags Initializer Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Run this command to create the meta_tags initializer file in your Rails application for configuration. ```bash rails generate meta_tags:install ``` -------------------------------- ### Serialize DateTime to ISO 8601 Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Demonstrates how datetime objects assigned to tag content are automatically serialized into ISO 8601 format during rendering. This is useful for time-related meta tags. ```ruby published_time = Time.parse("2024-01-15T10:30:00Z") tag = MetaTags::Tag.new(:meta, property: "article:published_time", content: published_time ) # The datetime is automatically serialized to ISO 8601 format html = tag.render(view) # => '' ``` -------------------------------- ### Access and Configure Global Meta Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/04-configuration.md Retrieve current configuration values or modify them globally using the MetaTags module. The configuration is a singleton and persists for the application's lifetime. ```ruby # Get configuration MetaTags.config.title_limit # => 70 # Configure MetaTags.configure do |config| config.title_limit = 100 end ``` -------------------------------- ### Set Image Source Meta Tag Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Configure the legacy image_src meta tag. Modern sharing typically uses Open Graph or card tags instead. ```ruby set_meta_tags image_src: "http://yoursite.com/icons/icon_32.png" # ``` -------------------------------- ### MetaTags::Tag#initialize Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/06-tag-classes.md Initializes a new instance of the Tag class. This class is used for HTML tags that do not have content or are self-closing, such as and . ```APIDOC ## initialize(name, attributes = {}) ### Description Initializes a new instance of Tag. ### Parameters #### Path Parameters - **name** (String, Symbol) - Required - HTML tag name (e.g., 'meta', 'link'). - **attributes** (Hash) - Optional - HTML tag attributes. Defaults to {}. ### Request Example ```ruby tag = MetaTags::Tag.new(:meta, name: "description", content: "Welcome") tag = MetaTags::Tag.new(:link, rel: "canonical", href: "https://example.com") ``` ``` -------------------------------- ### MetaTags::Configuration Class Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/COMPLETION.txt Manages the global configuration settings for the MetaTags gem. ```APIDOC ## MetaTags::Configuration ### Description Handles the configuration of the MetaTags gem, allowing customization of various aspects like default tags, separators, and rendering options. ### Configuration Attributes - **site_name** (String) - The name of the website. - **separator** (String) - The separator used in the full title. - **default_title** (String) - The default title if none is set. - **default_description** (String) - The default description if none is set. - **default_keywords** (String) - The default keywords if none are set. - **reverse_title** (Boolean) - Whether to reverse the title order (site name first). - **canonical_url** (String) - The canonical URL for the page. - **charset** (String) - The character set for the HTML document. - **viewport** (String) - The viewport meta tag content. - **open_meta_tags** (Boolean) - Whether to include Open Graph meta tags by default. - **twitter_card** (String) - The default Twitter card type. - **title_tag** (Boolean) - Whether to render the title tag. ### Methods - **reset_defaults!** - Resets all configuration options to their default values. - **default_property_tags** - Returns a hash of default property tags (e.g., Open Graph). - **open_meta_tags?** - Returns true if Open Graph tags are enabled, false otherwise. ### Example ```ruby MetaTags.configure do |config| config.site_name = 'My Awesome Blog' config.separator = ' | ' config.open_meta_tags = true end ``` ``` -------------------------------- ### Set Page Description Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/01-view-helper.md Sets the page description. HTML tags are stripped, and the string is truncated to the configured limit. ```ruby def description(description) set_meta_tags(description: description) description end ``` -------------------------------- ### Render Icon/Favicon Link Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/05-renderer.md Renders one or more icon or favicon link tags based on the provided configuration. ```ruby def render_icon(tags) icon = meta_tags.extract(:icon) return unless icon icon = [{href: icon}] if icon.is_a?(String) icon = [icon] if icon.is_a?(Hash) icon.each do |icon_params| icon_params = {rel: "icon", type: "image/x-icon"}.with_indifferent_access.merge(icon_params) tags << Tag.new(:link, icon_params) end end ``` -------------------------------- ### Legacy/Mobile Meta-Tags Configuration Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/11-setup-guide.md Use shorter limits and self-closing tags for compatibility with older or mobile systems. ```ruby MetaTags.configure do |config| # Shorter limits for older systems config.title_limit = 50 config.description_limit = 120 # Self-closing tags for XHTML config.open_meta_tags = false end ``` -------------------------------- ### Render Title Tag and Normalize Values Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/05-renderer.md Renders the title tag and populates `normalized_meta_tags` with title and site information. ```ruby def render_title(tags) normalized_meta_tags[:title] = meta_tags.page_title normalized_meta_tags[:site] = meta_tags[:site] title = meta_tags.extract_full_title normalized_meta_tags[:full_title] = title default_attributes = MetaTags.config.title_tag_attributes || {} if title.present? tags << ContentTag.new(:title, {content: title}.with_defaults(default_attributes)) end end ``` -------------------------------- ### Check Property Tag Configuration Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/11-setup-guide.md Verify the configuration for `property_tags` to ensure meta tags are rendered with the correct attributes (property vs. name). Tags listed in `property_tags` use the 'property' attribute; others use the 'name' attribute. ```ruby MetaTags.config.property_tags ``` -------------------------------- ### Set Multiple Meta Tags Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/01-view-helper.md Call this method multiple times to set various meta tags like title and description. Options are merged, and the last value for a key takes precedence. ```erb <% set_meta_tags title: 'Login Page', description: 'Here you can login' %> <% set_meta_tags canonical: 'https://example.com/login' %> ``` -------------------------------- ### Link Meta Tags Configuration Source: https://github.com/kpumuk/meta-tags/blob/main/_autodocs/08-types.md Configure link tags for canonical URLs, previous/next pages, AMP HTML, manifest, icons, and alternate language versions. ```ruby { canonical: "https://example.com/page", prev: "https://example.com/page?p=1", next: "https://example.com/page?p=3", amphtml: "https://example.com/page.amp", manifest: "/manifest.json", image_src: "/images/logo.png", icon: "/favicon.ico", alternate: { "fr" => "https://example.fr/page" } } ``` -------------------------------- ### Set Page Title Source: https://github.com/kpumuk/meta-tags/blob/main/README.md Set the page title meta tag. Can include a site name and optionally reverse the order. ```ruby set_meta_tags title: "Member Login" # Member Login ``` ```ruby set_meta_tags site: "Site Title", title: "Member Login" # Site Title | Member Login ``` ```ruby set_meta_tags site: "Site Title", title: "Member Login", reverse: true # Member Login | Site Title ```