0.0
Low commit activity in last 3 years
No release in over a year
A Ruby on Rails gem that facilitates fast retrieval of snippets of code or information for views.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 1.3.2
>= 0

Runtime

>= 5
>= 2.0.0
 Project Readme

Redis Snippets

Version Ruby Maintainability Coverage

Background

Easily store snippets of content in Redis. Inspired by plugin for Wordpress named Snippets.

With redis_snippets you could for instance store AdSense code snippets or other HTML/JS content.

Requirements

Gems:

  • rails 5.x or higher
  • redis
  • redis-namespace

Installation

Add to your Rails projects Gemfile and bundle install:

gem "redis_snippets"

Usage

It's a Rails engine so add redis-snippets to your Gemfile and put this in an initializer:

Rails.application.config.redis_snippets = {
  connection: ::Redis::Namespace.new("my_namespace", redis: ::Redis.new),
  keys: [:key1, :key2]
}

The names of the keys are entirely up to you.

You should then be able to access /admin/snippets/.

In your views use helper snippet().

<%= snippet(:key1) %>

Random snippets

One snippet area can include multiple snippets if you separate them with a

[section]

The snippet helper will randomly select the snippet. This is convenient for ad delivery or perhaps A/B testing 🤷‍♂.

Multi Site

If you're using one app to serve multiple sites a little more configuration is necessary.

Rails.application.config.redis_snippets = {
  connection: ::Redis::Namespace.new("my_namespace", redis: ::Redis.new),
  multi_site: true,
  keys: [:key1, :key2],
  transform: "MySnippetTransform"
}

Transforming Snippets

Sometimes you might want to transform snippets. This happens after randomization so you get the actual snippet content to be rendered passed to your transform class.

The transform class must respond to .transforms? and #transform. Example:

class MySnippetTransform
  def initialize(content:, key:)
    @content = content
    @key = key
  end

  # Must return content.
  def transform
    @content.gsub("Amazon", "Etsy")
  end

  class << self
    def transforms?(key:)
      key == :advert_header
    end
  end
end

I personally use this to insert special CSS code for AdSense. This saves me from having to do this manually whenever I update it or add it.

Rails.application.config.redis_snippets = {
  connection: ::Redis::Namespace.new("my_namespace", redis: ::Redis.new),
  multi_site: true,
  keys: [:key1, :key2],
  transform: "MySnippetTransform"
}

And add this method to your ApplicationController:

helper_method :redis_snippet_site_key
def redis_snippet_site_key
  request.host
end