DEV Community

Santosh Aryal
Santosh Aryal

Posted on

Short codes in Ruby on Rails

I was working on a Custom CMS developed by myself in Ruby on Rails. I wanted to use short codes to display the images into my pages. I am posting this part of my work here, which I posted in medium a year ago.

Image gallery in Pages, rendered with Short codes.

I was able to detect the short codes saved in db and convert into respective gallery. Its very easy and simple to do.

Create shortcodes of Gallery

Create a short codes of each gallery items like [media slug=”gallery”], each gallery has unique slug and are associated with the images or media uploads of any types. You can implement any of our own methods on creating gallery.

Add a helper to detect shortcode and display gallery.

I added a page_helper to detect the shortcode and convert the shortcode into the responsive gallery.

module PagesHelper
    def render_media_gallery(content)
      content.to_s.gsub(/\[media slug="([^"]+)"\]/) do |match|
        slug = $1
        uploads = MediaLibrary.friendly.find(slug).uploads
        if uploads.any?
            links = uploads.map do |upload|
              content_tag(:div, link_to(image_tag(upload.file, class: "img-responsive img-responsive-1x1 rounded border"), rails_blob_path(upload.file, disposition: "attachment")), class: "col")
            end.join("\n").html_safe

            content_tag(:div, links, class: "row row-cols-6 g-3", "data-controller": "lightbox")
          else
            "Media not found for slug: #{slug}"
          end
      end.html_safe
    end
end
Enter fullscreen mode Exit fullscreen mode

For references, following are the models used to create a media manager with the power of Rails and StimulusController.

class MediaLibrary < ApplicationRecord
  has_many :uploads
  extend FriendlyId
  friendly_id :slug_candidates, use: :slugged

  def slug_candidates
      [:name] + Array.new(6) {|index| [:name, index+2]}
  end

  def should_generate_new_friendly_id? #will change the slug if the name changed
    name_changed? || super
  end
end
Enter fullscreen mode Exit fullscreen mode
class Upload < ApplicationRecord
    belongs_to :media_library, optional:  true
    has_one_attached :file, dependent: :destroy
end
Enter fullscreen mode Exit fullscreen mode

Thank you! Happy Coding.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post