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.

Top comments (0)