a DRY singleton Active Record in Ruby on Rails

This is to document that which is scattered or implied so hopeful this will save you (and me) from having to hunt and gather.

These examples are based on Ruby 2 and Ruby on Rails 4 and the “acts_as_singleton” gem (RubyGems : acts_as_singleton and GitHub : acts_as_singleton) with a big shout out to Stephen Celis

a Singleton is a design pattern that exists to address a problem where you want to represent an object; and only one of that object can exist at any time, no more.

So what is the use case for a ActiveRecord singleton as opposed to a key value YAML file or a A key-value table? Having all that data in a db means your data is in one local not is text files and the file system, and you can use all the ActiveRecord model goodness. Is it overkill, yea maybe but it just works.

1
2
3
4
class Group < ActiveRecord::Base

  acts_as_singleton
end

a very dry controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class GroupsController < ApplicationController
  before_action :set_group, only: [:index, :edit, :update]

  # PATCH/PUT /groups/1
  def update
    @group = Group.instance

    respond_to do |format|
      if @admin_group.update(group_params)
        format.html { redirect_to groups_path, notice: 'Group was successfully updated.' }
      else
        format.html { render action: 'edit' }
      end
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_group
      @group =  Group.instance
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def admin_group_params
#      params[:group]
      params.require(:group).permit!  #very bad lazy thing todo
    end
end

update redirects to the index view

and you only need a index and edit views, nothing special there, although the edit returns and goes back to the index not the show view

Leave a Reply