### Setup ButterCMS Ruby Client Source: https://github.com/buttercms/buttercms-ruby/blob/master/README.md Installs the ButterCMS Ruby gem and sets the API token. Optionally configures test mode and read/open timeouts for API requests. This is essential for authenticating and connecting to the ButterCMS API. ```ruby require 'buttercms-ruby' ButterCMS::api_token = "YourToken" # Fetch content from test mode (eg. for your staging website) # ButterCMS::test_mode = true # Set read timeout (Default is 5.0) # ButterCMS::read_timeout = 5.0 # Set open timeout (Default is 2.0) # ButterCMS::open_timeout = 2.0 ``` -------------------------------- ### Install and Configure ButterCMS Ruby Client Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Instructions for installing the ButterCMS Ruby gem and configuring API tokens and optional settings like test mode and timeouts. Requires the 'buttercms-ruby' gem. ```ruby require 'buttercms-ruby' ButterCMS::api_token = "your_api_read_token_here" ButterCMS::write_api_token = "your_api_write_token_here" # For create/update operations # Optional: Enable test mode for staging/preview content ButterCMS::test_mode = true # Optional: Set HTTP timeouts ButterCMS::read_timeout = 10.0 # Default: 5.0 seconds ButterCMS::open_timeout = 5.0 # Default: 2.0 seconds ``` -------------------------------- ### Manage Collections with ButterCMS Ruby Client Source: https://github.com/buttercms/buttercms-ruby/blob/master/README.md Provides examples for listing instances of a specific collection or multiple collections using the ButterCMS Ruby client. It shows how to fetch collections with pagination metadata and supports test mode for previewing content. ```ruby # list each instance of a given collection with meta data for fetching the next page. params = { page: 1, page_size: 10, locale: 'en', preview: 1, 'fields.headline': 'foo bar', levels: 2 } # optional ButterCMS::Content.list('collection1', params) # list instances for multiple collections, this will not return meta data for pagination control. ButterCMS::Content.fetch(['collection1', 'collection2'], params) # Test mode can be used to setup a staging website for previewing Collections or for testing content during local development. To fetch content from test mode add the following configuration: ButterCMS::test_mode = true ``` -------------------------------- ### Search All Pages with Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Provides an example of searching across all page types in ButterCMS using the Ruby SDK. It demonstrates how to use search terms and pagination parameters, and iterate through the results. ```ruby # Search across all page types search_results = ButterCMS::Page.search('product launch', { page: 1, page_size: 20 }) search_results.each do |page| puts "Found: #{page.name} (#{page.slug})" puts "Type: #{page.page_type}" end ``` -------------------------------- ### Retrieve All Tags in Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Provides a Ruby code example for fetching a list of all tags used in ButterCMS. It iterates through the tags and prints their names and slugs. ```ruby # List all tags tags = ButterCMS::Tag.all tags.each do |tag| puts tag.name puts tag.slug end ``` -------------------------------- ### Create New Blog Post Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Provides a code example for creating a new blog post via the ButterCMS Ruby client. It includes specifying various attributes like slug, title, body, status, author, categories, and tags. Requires write API token configuration. ```ruby # Ensure write token is configured ButterCMS::write_api_token = "your_write_token" # Create post new_post = ButterCMS::Post.create({ slug: 'my-new-blog-post', title: 'My Amazing Blog Post', body: '
This is the full HTML content of the post.
', summary: 'A brief summary of the post', status: 'published', # or 'draft' featured_image: 'https://example.com/image.jpg', seo_title: 'SEO Optimized Title', meta_description: 'Meta description for search engines', author_id: 12345, categories: ['Technology', 'Programming'], tags: ['Ruby', 'API'] }) # Access created post puts "Created post: #{new_post.slug}" puts "Status: #{new_post.status}" ``` -------------------------------- ### Retrieve All Authors in Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Provides a Ruby code example for fetching a list of all authors from ButterCMS, including pagination parameters. It shows how to iterate through the authors and access their details. ```ruby # List all authors authors = ButterCMS::Author.all(page: 1, page_size: 20) authors.each do |author| puts author.first_name puts author.last_name puts author.email puts author.slug puts author.bio puts author.profile_image end ``` -------------------------------- ### Preview Unpublished Content with ButterCMS (Ruby) Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Shows how to retrieve unpublished or draft content from ButterCMS using the `preview` parameter. It includes examples for fetching only published content, including all content (published and drafts), and a conditional check using a preview token for secure access to draft content. ```ruby # Fetch only published content (default) published = ButterCMS::Page.list('news') # Include draft/unpublished content all_content = ButterCMS::Page.list('news', preview: 1) # Useful for preview environments if params[:preview_token] == ENV['PREVIEW_SECRET'] pages = ButterCMS::Page.list('news', preview: 1) else pages = ButterCMS::Page.list('news') end ``` -------------------------------- ### Fetch Locale-Specific Content with ButterCMS (Ruby) Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Demonstrates how to fetch content from ButterCMS in different locales (languages). It shows examples for fetching English, Spanish, and French content, including a fallback mechanism to English if French content is not available. This is essential for internationalized applications. ```ruby # Fetch English content en_pages = ButterCMS::Page.list('products', locale: 'en') en_pages.each { |p| puts p.fields.title } # Fetch Spanish content es_pages = ButterCMS::Page.list('products', locale: 'es') es_pages.each { |p| puts p.fields.title } # Fetch French content with fallback fr_pages = ButterCMS::Page.list('products', locale: 'fr') if fr_pages.count == 0 puts "No French content, using English" fr_pages = ButterCMS::Page.list('products', locale: 'en') end ``` -------------------------------- ### List Pages of Specific Type Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Example of listing pages of a specific content type (e.g., 'news') using the ButterCMS Ruby client. Supports filtering by locale, including unpublished content, and controlling nesting depth. Requires API token configuration. ```ruby # List all pages of type 'news' params = { page: 1, page_size: 10, locale: 'en', # Filter by language preview: 1, # Include unpublished content levels: 2 # Nesting depth for related data } pages = ButterCMS::Page.list('news', params) ``` -------------------------------- ### Filter Collections by Custom Fields with ButterCMS (Ruby) Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Illustrates how to filter content collections (like recipes or blog posts) based on custom field values in ButterCMS. Examples include filtering by a single field ('difficulty'), multiple fields ('cuisine', 'category'), and filtering pages by a boolean-like custom field ('featured'). ```ruby # Filter collections by custom field values beginner_recipes = ButterCMS::Content.list('recipes', { 'fields.difficulty': 'beginner', page_size: 20 }) # Filter by multiple fields italian_pasta = ButterCMS::Content.list('recipes', { 'fields.cuisine': 'italian', 'fields.category': 'pasta', page_size: 50 }) # Filter pages by custom field featured = ButterCMS::Page.list('blog', { 'fields.featured': 'true' }) ``` -------------------------------- ### Create New Page with Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Illustrates how to create a new page using the ButterCMS Ruby SDK, including setting the slug, title, status, page type, and various custom fields, such as text blocks and images. ```ruby # Create page with custom fields new_page = ButterCMS::Page.create({ slug: 'about-us-page', title: 'About Us', status: 'published', # 'published' or 'draft' 'page-type': 'company_page', fields: { meta_title: 'About Our Company - Best Services', meta_description: 'Learn about our company history and values', headline: 'About Our Company', subheadline: 'Building great products since 2010', hero_image: 'https://example.com/hero.jpg', content_blocks: [ { type: 'text', body: 'Our company story...' }, { type: 'image', url: 'https://example.com/team.jpg' } ] } }) puts "Created page: #{new_page.slug}" ``` -------------------------------- ### Manage Blog Posts with ButterCMS Ruby Client Source: https://github.com/buttercms/buttercms-ruby/blob/master/README.md Illustrates how to retrieve, search, find, create, and update blog posts using the ButterCMS Ruby client. Requires a separate write API token for create and update operations. Handles blog post content management. ```ruby posts = ButterCMS::Post.all({:page => 1, :page_size => 10}) puts posts.first.title puts posts.meta.next_page posts = ButterCMS::Post.search("my favorite post", {page: 1, page_size: 10}) puts posts.first.title post = ButterCMS::Post.find("post-slug") puts post.title # Create a Post. ButterCMS::write_api_token = "YourWriteToken" ButterCMS::Post.create({ slug: 'blog-slug', title: 'blog-title' }) # Update a Post ButterCMS::Post.update('blog-slug', { title: 'blog-title-v2' }) ``` -------------------------------- ### Retrieve and Iterate Through Blog Posts Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Demonstrates how to fetch a paginated list of blog posts using the ButterCMS Ruby client and iterate through the results. Accesses post details and pagination metadata. Requires API token configuration. ```ruby # List posts with pagination posts = ButterCMS::Post.all(page: 1, page_size: 10) # Iterate through posts collection posts.each do |post| puts post.title puts post.slug puts post.published puts post.author.first_name puts post.author.last_name end # Access pagination metadata puts "Current page: #{posts.meta.count}" puts "Next page: #{posts.meta.next_page}" puts "Previous page: #{posts.meta.previous_page}" # Get first post first_post = posts.first puts first_post.body puts first_post.summary ``` -------------------------------- ### Manage Pages with ButterCMS Ruby Client Source: https://github.com/buttercms/buttercms-ruby/blob/master/README.md Demonstrates how to list, retrieve, and search for pages using the ButterCMS Ruby client. Supports optional parameters like page number, page size, locale, preview mode, and custom fields. Used for fetching content of type 'page'. ```ruby params = {page: 1, page_size: 10, locale: 'en', preview: 1, 'fields.headline': 'foo bar', levels: 2} # optional pages = ButterCMS::Page.list('news', params) page = ButterCMS::Page.get('news', 'hello-world', params) pages = ButterCMS::Page.search('query', params) ``` -------------------------------- ### Search Blog Posts by Query Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Illustrates how to search for blog posts based on a query string using the ButterCMS Ruby client. Returns paginated results and provides a way to check if any posts were found. Requires API token configuration. ```ruby # Search with query string results = ButterCMS::Post.search("ruby programming", page: 1, page_size: 10) results.each do |post| puts "#{post.title} - #{post.slug}" end # Check if results exist if results.count > 0 puts "Found #{results.meta.count} results" else puts "No posts found" end ``` -------------------------------- ### Manage Pages (Create/Update) with ButterCMS Ruby Client Source: https://github.com/buttercms/buttercms-ruby/blob/master/README.md Demonstrates the creation and updating of pages using the ButterCMS Ruby client. Specifies required fields like slug, title, status, page type, and custom fields for page content management. ```ruby # Create a page ButterCMS::Page.create({ slug: 'page-slug', title: 'page-title', status: 'published', "page-type": 'page_type', fields: { meta_title: 'test meta title' } }) # update a Page ButterCMS::Page.update('page-slug-2', { status: 'published', fields: { meta_title: 'test meta title' } }) ``` -------------------------------- ### Retrieve All Categories in Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Shows a simple Ruby code snippet for listing all blog categories available in ButterCMS. It iterates through the categories and prints their names and slugs. ```ruby # List all blog categories categories = ButterCMS::Category.all categories.each do |category| puts category.name puts category.slug end ``` -------------------------------- ### Configure YAML Store Source: https://context7.com/buttercms/buttercms-ruby/llms.txt This section details how to configure ButterCMS to use a YAML file for caching, providing offline resilience and faster responses. ```APIDOC ## Configure YAML Store ### Description Sets up ButterCMS to use a local YAML file for caching API responses, enabling graceful degradation during API outages. ### Method Configuration ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby # Use YAML file for caching ButterCMS::data_store = :yaml, "/tmp/buttercms_cache.store" # Optional: Set custom logger ButterCMS::logger = Logger.new('log/buttercms.log') # Normal API usage - responses are cached automatically posts = ButterCMS::Post.all(page: 1) # On success: API response is cached to YAML file # On failure: Returns cached response if available # Subsequent requests use cache on API failure begin posts = ButterCMS::Post.all(page: 1) # If API is down, cached data is returned puts "Using cached data" if posts rescue ButterCMS::Error => e # Only raised if cache is empty puts "No cached data available" end ``` ### Response N/A (Configuration affects SDK behavior) ``` -------------------------------- ### Test Mode for Staging Content Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Explains how to use the `test_mode` flag in the ButterCMS Ruby SDK to fetch staging or draft content for testing purposes. ```APIDOC ## Test Mode for Staging Content ### Description Enables testing of staging or draft content by setting the `test_mode` flag to `true`, allowing previews without affecting live production content. ### Method Configuration / Feature Flag ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby # Configure for production ButterCMS::api_token = "production_token" ButterCMS::test_mode = false production_posts = ButterCMS::Post.all # Returns published content # Configure for staging/preview ButterCMS::api_token = "production_token" ButterCMS::test_mode = true staging_posts = ButterCMS::Post.all # Returns draft/preview content for testing # Toggle based on environment if Rails.env.staging? ButterCMS::test_mode = true end ``` ### Response N/A (Affects which content is returned by API calls) ``` -------------------------------- ### Test Mode Configuration Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Configure test mode for staging and preview content. Toggle between published content for production and draft/preview content for testing environments, with Rails environment integration. ```ruby # Configure for production ButterCMS::api_token = "production_token" ButterCMS::test_mode = false production_posts = ButterCMS::Post.all # Returns published content # Configure for staging/preview ButterCMS::api_token = "production_token" ButterCMS::test_mode = true staging_posts = ButterCMS::Post.all # Returns draft/preview content for testing # Toggle based on environment if Rails.env.staging? ButterCMS::test_mode = true end ``` -------------------------------- ### List Single Collection with Pagination in Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Explains how to retrieve items from a specific collection (e.g., 'recipes') using the ButterCMS Ruby SDK, including pagination parameters and filtering by custom fields. It also shows how to access pagination metadata. ```ruby # Retrieve items from a collection with metadata params = { page: 1, page_size: 10, locale: 'en', preview: 1, 'fields.difficulty': 'beginner', # Filter by custom field levels: 2 } recipes = ButterCMS::Content.list('recipes', params) # Access collection items recipes.each do |recipe| puts recipe.name puts recipe.description puts recipe.ingredients puts recipe.prep_time puts recipe.difficulty puts recipe.author_name end # Pagination metadata available puts "Total recipes: #{recipes.meta.count}" puts "Next page: #{recipes.meta.next_page}" ``` -------------------------------- ### Configure Redis Store Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Explains how to configure ButterCMS to use Redis for distributed caching, enhancing performance and availability across multiple instances. ```APIDOC ## Configure Redis Store ### Description Configures ButterCMS to use Redis for caching, allowing for distributed caching and improved resilience. ### Method Configuration ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby # Use Redis for distributed caching ButterCMS::data_store = :redis, ENV['REDIS_URL'] # Or with explicit URL ButterCMS::data_store = :redis, 'redis://localhost:6379/0' # API requests cache to Redis post = ButterCMS::Post.find('my-post') # Cached with key: "buttercms:/posts/my-post/:{}" # Cache survives API outages post = ButterCMS::Post.find('my-post') # Returns Redis cached version if API fails ``` ### Response N/A (Configuration affects SDK behavior) ``` -------------------------------- ### Fetch Multiple Collections in Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Shows how to retrieve data from multiple collections (e.g., 'recipes', 'chefs', 'categories') in a single request using the ButterCMS Ruby SDK. It details accessing data for each collection separately. ```ruby # Retrieve multiple collections in single request (no pagination) multi_content = ButterCMS::Content.fetch(['recipes', 'chefs', 'categories'], { locale: 'en', levels: 2 }) # Access each collection separately puts "Recipes:" multi_content.data.recipes.each do |recipe| puts "- #{recipe.name}" end puts "\nChefs:" multi_content.data.chefs.each do |chef| puts "- #{chef.name} (#{chef.specialty})" end puts "\nCategories:" multi_content.data.categories.each do |category| puts "- #{category.name}" end ``` -------------------------------- ### Configure Fallback Data Store for ButterCMS Ruby Client Source: https://github.com/buttercms/buttercms-ruby/blob/master/README.md Configures the ButterCMS Ruby client to use a fallback data store (YAML or Redis) for resilience against API request failures. It also shows how to set a custom logger for the client. ```ruby # Use YAMLstore ButterCMS::data_store = :yaml, "/File/Path/For/buttercms.store" # Use Redis ButterCMS::data_store = :redis, ENV['REDIS_URL'] # Use Redis over ssl store ButterCMS.data_store = :redis_ssl, ENV["REDIS_URL"], { ca_file: "/path/to/ca.crt" } # Set logger (optional) ButterCMS::logger = MyLogger.new ``` -------------------------------- ### Graceful Degradation with Cache Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Demonstrates how to combine caching mechanisms with error handling to ensure application availability even when the ButterCMS API is temporarily unavailable. ```APIDOC ## Graceful Degradation with Cache ### Description Implements a strategy for graceful degradation by using a fallback cache (Redis in this example) when the ButterCMS API is unreachable, ensuring data availability. ### Method Error Handling / Caching Strategy ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby # Configure fallback store ButterCMS::data_store = :redis, ENV['REDIS_URL'] ButterCMS::logger = Logger.new(STDOUT) def fetch_posts_safely begin posts = ButterCMS::Post.all(page: 1, page_size: 10) # Success: Fresh data from API, also cached return posts rescue ButterCMS::Error, StandardError => e # API failed but cache returned data # Logger shows: "Fetched key buttercms:/posts/:..." # Returns cached posts array return nil unless posts # No cache available puts "Using cached data due to: #{e.message}" return posts end end posts = fetch_posts_safely if posts posts.each { |p| puts p.title } else puts "No data available" end ``` ### Response N/A (Illustrates a resilient data fetching pattern) ``` -------------------------------- ### Handle Create/Update Errors Source: https://context7.com/buttercms/buttercms-ruby/llms.txt This section focuses on handling specific errors that can occur during content creation or updates via the ButterCMS API. ```APIDOC ## Handle Create/Update Errors ### Description Provides guidance on handling errors, particularly `BadRequest`, when creating or updating content using the ButterCMS API, focusing on validation issues. ### Method Error Handling ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby ButterCMS::write_api_token = "your_write_token" try # Attempt to create post with invalid data post = ButterCMS::Post.create({ slug: '', # Invalid: empty slug title: '' # Invalid: empty title }) rescue ButterCMS::BadRequest => e puts "Validation failed: #{e.message}" # Example: "slug: This field is required. title: This field is required." rescue ButterCMS::Unauthorized => e puts "Write token invalid: #{e.message}" # Check write_api_token configuration end ``` ### Response N/A (Illustrates error handling logic) ``` -------------------------------- ### Retrieve Authors, Categories, Tags, and Feeds with ButterCMS Ruby Client Source: https://github.com/buttercms/buttercms-ruby/blob/master/README.md Shows how to retrieve author details by slug, category details by slug, all tags, and RSS feeds using the ButterCMS Ruby client. Used for accessing metadata and feed content from the CMS. ```ruby author = ButterCMS::Author.find("author-slug") puts author.first_name category = ButterCMS::Category.find("category-slug") puts category.name tags = ButterCMS::Tag.all p tags rss_feed = ButterCMS::Feed.find(:rss) puts rss_feed.data ``` -------------------------------- ### Cache Store Configuration Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Configure different cache stores for offline resilience and improved performance. Supports YAML file storage, standard Redis connections, and Redis with SSL/TLS encryption for secure distributed caching. ```ruby # Use YAML file for caching ButterCMS::data_store = :yaml, "/tmp/buttercms_cache.store" # Optional: Set custom logger ButterCMS::logger = Logger.new('log/buttercms.log') # Normal API usage - responses are cached automatically posts = ButterCMS::Post.all(page: 1) # On success: API response is cached to YAML file # On failure: Returns cached response if available # Subsequent requests use cache on API failure begin posts = ButterCMS::Post.all(page: 1) # If API is down, cached data is returned puts "Using cached data" if posts rescue ButterCMS::Error => e # Only raised if cache is empty puts "No cached data available" end ``` ```ruby # Use Redis for distributed caching ButterCMS::data_store = :redis, ENV['REDIS_URL'] # Or with explicit URL ButterCMS::data_store = :redis, 'redis://localhost:6379/0' # API requests cache to Redis post = ButterCMS::Post.find('my-post') # Cached with key: "buttercms:/posts/my-post/:{}" # Cache survives API outages post = ButterCMS::Post.find('my-post') # Returns Redis cached version if API fails ``` ```ruby # Use Redis over SSL/TLS ButterCMS::data_store = :redis_ssl, ENV['REDIS_URL'], { ca_file: "/path/to/ca-certificates.crt" } # All API requests cache securely pages = ButterCMS::Page.list('news', page: 1) # Cached to Redis over encrypted connection # Fallback works transparently pages = ButterCMS::Page.list('news', page: 1) # Uses cached data on API failure ``` -------------------------------- ### Handle All API Errors Source: https://context7.com/buttercms/buttercms-ruby/llms.txt This section outlines how to implement comprehensive error handling for various ButterCMS API exceptions, including network issues. ```APIDOC ## Handle All API Errors ### Description Demonstrates robust error handling for ButterCMS API requests, catching specific exceptions like Not Found, Unauthorized, and Bad Request, as well as general errors. ### Method Error Handling ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby require 'buttercms-ruby' ButterCMS::api_token = "your_token" try # Attempt to fetch non-existent post post = ButterCMS::Post.find("non-existent-slug") puts post.title rescue ButterCMS::NotFound => e puts "Post not found: #{e.message}" # Handle 404 errors rescue ButterCMS::Unauthorized => e puts "Authentication failed: #{e.message}" # Invalid API token - check credentials rescue ButterCMS::BadRequest => e puts "Bad request: #{e.message}" # Validation error - check parameters rescue ButterCMS::Error => e puts "ButterCMS error: #{e.message}" # Catch-all for other ButterCMS errors rescue StandardError => e puts "Unexpected error: #{e.message}" # Network errors, timeouts, etc. end ``` ### Response N/A (Illustrates error handling logic) ``` -------------------------------- ### Update Existing Blog Post Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Demonstrates how to update an existing blog post using its slug with the ButterCMS Ruby client. Allows modification of properties like title, body, status, and featured image. Requires write API token configuration. ```ruby # Update post by slug updated_post = ButterCMS::Post.update('my-new-blog-post', { title: 'Updated Blog Post Title', body: 'Updated content with new information.
', status: 'draft', featured_image: 'https://example.com/new-image.jpg' }) puts "Updated: #{updated_post.title}" puts "Status: #{updated_post.status}" ``` -------------------------------- ### Find Single Blog Post by Slug Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Shows how to retrieve a specific blog post by its slug using the ButterCMS Ruby client. Includes accessing various post properties and nested data like author, categories, and tags. Requires API token configuration. ```ruby # Retrieve specific post post = ButterCMS::Post.find("example-blog-post-slug") # Access post properties puts post.title # Post title puts post.slug # URL slug puts post.body # Full content puts post.summary # Excerpt/summary puts post.published # Publication date puts post.featured_image # Image URL puts post.seo_title # SEO meta title puts post.meta_description # SEO meta description # Access nested author data puts post.author.first_name puts post.author.last_name puts post.author.email puts post.author.slug # Access categories and tags post.categories.each { |cat| puts cat.name } post.tags.each { |tag| puts tag.name } ``` -------------------------------- ### Configure ButterCMS Client for Slow Networks (Ruby) Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Configures the ButterCMS client with custom read and open timeouts to handle slow network conditions. This is useful for ensuring your application remains responsive even when the CMS API is slow to respond. It also demonstrates basic error handling for read timeouts. ```ruby ButterCMS::api_token = "your_token" ButterCMS::read_timeout = 15.0 # Wait up to 15 seconds for response ButterCMS::open_timeout = 10.0 # Wait up to 10 seconds to connect # Make request with extended timeouts begin posts = ButterCMS::Post.all rescue Net::ReadTimeout => e puts "Request took too long" end ``` -------------------------------- ### Configure Redis with SSL Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Provides instructions on configuring ButterCMS to use Redis with SSL/TLS encryption for secure data caching. ```APIDOC ## Configure Redis with SSL ### Description Sets up ButterCMS to cache data in Redis using a secure SSL/TLS connection. ### Method Configuration ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby # Use Redis over SSL/TLS ButterCMS::data_store = :redis_ssl, ENV['REDIS_URL'], { ca_file: "/path/to/ca-certificates.crt" } # All API requests cache securely pages = ButterCMS::Page.list('news', page: 1) # Cached to Redis over encrypted connection # Fallback works transparently pages = ButterCMS::Page.list('news', page: 1) # Uses cached data on API failure ``` ### Response N/A (Configuration affects SDK behavior) ``` -------------------------------- ### Update Existing Page with Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Demonstrates how to update an existing page's properties and custom fields using the ButterCMS Ruby SDK. It shows how to modify fields like status, meta title, headline, and content blocks. ```ruby # Update page fields updated_page = ButterCMS::Page.update('about-us-page', { status: 'published', fields: { meta_title: 'Updated Meta Title', headline: 'New Headline Text', content_blocks: [ { type: 'text', body: 'Updated content here' } ] } }) puts "Updated page status: #{updated_page.status}" ``` -------------------------------- ### Iterate and Access Page Data in Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Demonstrates how to iterate through a collection of pages, access their properties like slug and published status, and retrieve custom fields defined in the ButterCMS dashboard. Also shows how to access pagination metadata. ```ruby # Iterate through pages pages.each do |page| puts page.slug puts page.published # Access custom fields (defined in ButterCMS dashboard) puts page.fields.headline puts page.fields.subheadline puts page.fields.hero_image puts page.fields.seo_title end # Pagination puts "Total pages: #{pages.meta.count}" puts "Next page number: #{pages.meta.next_page}" if pages.meta.next_page ``` -------------------------------- ### Create/Update Error Handling Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Handle validation and authorization errors when creating or updating content through ButterCMS write API. Manages invalid data submission and authentication failures with specific error messages. ```ruby ButterCMS::write_api_token = "your_write_token" begin # Attempt to create post with invalid data post = ButterCMS::Post.create({ slug: '', # Invalid: empty slug title: '' # Invalid: empty title }) rescue ButterCMS::BadRequest => e puts "Validation failed: #{e.message}" # Example: "slug: This field is required. title: This field is required." rescue ButterCMS::Unauthorized => e puts "Write token invalid: #{e.message}" # Check write_api_token configuration end ``` -------------------------------- ### Generate Atom Feed Source: https://context7.com/buttercms/buttercms-ruby/llms.txt This section explains how to generate and use the Atom feed from ButterCMS, similar to the RSS feed functionality. ```APIDOC ## Generate Atom Feed ### Description Retrieves the Atom feed from ButterCMS and shows how to output or save its content. ### Method GET ### Endpoint `/feeds/atom` (Implicitly called by the SDK) ### Parameters None ### Request Example ```ruby # Get Atom feed atom_feed = ButterCMS::Feed.find(:atom) # Output XML content puts atom_feed.data # Write to file File.write('public/atom.xml', atom_feed.data) ``` ### Response #### Success Response (200) - **data** (string) - The XML content of the Atom feed. ``` -------------------------------- ### Custom Timeout Configuration Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Details how to configure custom timeout settings for API requests made by the ButterCMS Ruby SDK. ```APIDOC ## Custom Timeout Configuration ### Description Allows setting a custom timeout duration for HTTP requests made by the ButterCMS SDK to prevent excessively long waits for API responses. ### Method Configuration ### Endpoint N/A ### Parameters N/A ### Request Example ```ruby # Set a custom timeout for all requests (e.g., 10 seconds) ButterCMS.connection_options = { timeout: 10 } # Or configure for specific requests if needed (SDK might not directly support per-request) # Refer to underlying HTTP client configuration if available # Example usage (behavior is now subject to the set timeout) begin posts = ButterCMS::Post.all rescue Net::ReadTimeout => e puts "Request timed out: #{e.message}" rescue StandardError => e puts "An error occurred: #{e.message}" end ``` ### Response N/A (Configuration affects network request behavior) ``` -------------------------------- ### Retrieve and Access Single Page Data in Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Shows how to retrieve a specific page by its type and slug using the ButterCMS Ruby SDK. It details accessing page properties and custom fields, including nested components like related posts. ```ruby # Retrieve specific page by type and slug page = ButterCMS::Page.get('news', 'hello-world-post', {levels: 2, locale: 'en'}) # Access page properties puts page.slug puts page.name puts page.published puts page.updated # Access custom fields specific to page type puts page.fields.headline puts page.fields.author_name puts page.fields.hero_image puts page.fields.content_sections # Array of content blocks # Access nested components page.fields.related_posts.each do |related| puts related.title puts related.slug end ``` -------------------------------- ### Generate RSS Feed Source: https://context7.com/buttercms/buttercms-ruby/llms.txt This section demonstrates how to retrieve and utilize the RSS feed from ButterCMS, including saving it to a file or using it within a Rails controller. ```APIDOC ## Generate RSS Feed ### Description Retrieves the RSS feed from ButterCMS and shows how to output or save its content. ### Method GET ### Endpoint `/feeds/rss` (Implicitly called by the SDK) ### Parameters None ### Request Example ```ruby # Get RSS feed rss_feed = ButterCMS::Feed.find(:rss) # Output XML content puts rss_feed.data # Write to file File.write('public/rss.xml', rss_feed.data) # Use in Rails controller class FeedController < ApplicationController def rss @feed = ButterCMS::Feed.find(:rss) render xml: @feed.data end end ``` ### Response #### Success Response (200) - **data** (string) - The XML content of the RSS feed. ``` -------------------------------- ### Atom Feed Generation Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Generate Atom feeds using ButterCMS Feed API. Retrieves Atom feed data and outputs XML content to console or writes to file. ```ruby # Get Atom feed atom_feed = ButterCMS::Feed.find(:atom) # Output XML content puts atom_feed.data # Write to file File.write('public/atom.xml', atom_feed.data) ``` -------------------------------- ### Find Single Author by Slug in Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Demonstrates how to retrieve a single author's details by their unique slug using the ButterCMS Ruby SDK. It shows accessing author properties and using the data in an application. ```ruby # Get author by slug author = ButterCMS::Author.find("john-doe") puts "Name: #{author.first_name} #{author.last_name}" puts "Email: #{author.email}" puts "Bio: #{author.bio}" puts "Profile: #{author.profile_image}" puts "Slug: #{author.slug}" # Use author data in application author_name = "#{author.first_name} #{author.last_name}" puts "Articles by #{author_name}" ``` -------------------------------- ### API Error Handling Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Comprehensive error handling for all ButterCMS API operations. Handles authentication errors, validation errors, not found errors, and general API errors with specific rescue blocks and error messages. ```ruby require 'buttercms-ruby' ButterCMS::api_token = "your_token" begin # Attempt to fetch non-existent post post = ButterCMS::Post.find("non-existent-slug") puts post.title rescue ButterCMS::NotFound => e puts "Post not found: #{e.message}" # Handle 404 errors rescue ButterCMS::Unauthorized => e puts "Authentication failed: #{e.message}" # Invalid API token - check credentials rescue ButterCMS::BadRequest => e puts "Bad request: #{e.message}" # Validation error - check parameters rescue ButterCMS::Error => e puts "ButterCMS error: #{e.message}" # Catch-all for other ButterCMS errors rescue StandardError => e puts "Unexpected error: #{e.message}" # Network errors, timeouts, etc. end ``` -------------------------------- ### Graceful Degradation with Cache Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Implement resilient API behavior by combining error handling with cache fallback. When API calls fail, automatically returns cached data while logging the failure for monitoring purposes. ```ruby # Configure fallback store ButterCMS::data_store = :redis, ENV['REDIS_URL'] ButterCMS::logger = Logger.new(STDOUT) def fetch_posts_safely begin posts = ButterCMS::Post.all(page: 1, page_size: 10) # Success: Fresh data from API, also cached return posts rescue ButterCMS::Error, StandardError => e # API failed but cache returned data # Logger shows: "Fetched key buttercms:/posts/:..." # Returns cached posts array return nil unless posts # No cache available puts "Using cached data due to: #{e.message}" return posts end end posts = fetch_posts_safely if posts posts.each { |p| puts p.title } else puts "No data available" end ``` -------------------------------- ### Find Single Category by Slug in Ruby Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Illustrates how to retrieve a specific category by its slug using the ButterCMS Ruby SDK. It shows accessing the category's name and slug, and then using the slug to filter blog posts. ```ruby # Get category by slug category = ButterCMS::Category.find("ruby-programming") puts "Category: #{category.name}" puts "Slug: #{category.slug}" # Use for filtering posts posts = ButterCMS::Post.all(category_slug: category.slug) ``` -------------------------------- ### Tag-based Content Filtering Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Filter blog posts by tags using the ButterCMS API. Retrieves the first tag from a collection and fetches all posts associated with that specific tag slug. ```ruby if tags.count > 0 first_tag = tags.first tagged_posts = ButterCMS::Post.all(tag_slug: first_tag.slug) end ``` -------------------------------- ### RSS Feed Generation Source: https://context7.com/buttercms/buttercms-ruby/llms.txt Generate RSS feeds using ButterCMS Feed API. Retrieves RSS feed data, outputs XML content, writes to file, and integrates with Rails controllers. ```ruby # Get RSS feed rss_feed = ButterCMS::Feed.find(:rss) # Output XML content puts rss_feed.data # Write to file File.write('public/rss.xml', rss_feed.data) # Use in Rails controller class FeedController < ApplicationController def rss @feed = ButterCMS::Feed.find(:rss) render xml: @feed.data end end ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.