Skip to content

Instantly share code, notes, and snippets.

@bradly
Created April 26, 2013 17:28

Revisions

  1. bradly created this gist Apr 26, 2013.
    31 changes: 31 additions & 0 deletions active_record_singleton.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    module ActiveRecordSingleton
    def self.included(base)
    base.class_eval do
    class << self
    delegate :attributes, :save, :save!, :update_attribute, :update_attributes, :update_attributes!, :update_column, to: 'instance'

    [:new, :create, :create!, :destroy, :destroy_all, :delete, :delete_all].each do |method_name|
    undef_method method_name
    end

    def instance
    @@singleton ||= self.first_or_create!
    end
    end

    [:destroy, :delete, :clone, :dup].each do |method_name|
    undef_method method_name
    end

    column_names.each do |column_name|
    define_singleton_method column_name.to_sym do
    instance.send(column_name.to_sym)
    end

    define_singleton_method :"#{column_name}=" do |value|
    instance.send(:"#{column_name}=", value)
    end
    end
    end
    end
    end
    3 changes: 3 additions & 0 deletions settings.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    class Settings < ActiveRecord::Base
    include ActiveRecordSingleton
    end