Skip to content

Instantly share code, notes, and snippets.

@bradly
Created April 26, 2013 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bradly/5468887 to your computer and use it in GitHub Desktop.
Save bradly/5468887 to your computer and use it in GitHub Desktop.
A simple lib to make an active record class work with a single row. Not sure how I feel about it yet, but it really came in handy in a current app.
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
class Settings < ActiveRecord::Base
include ActiveRecordSingleton
end
@bradly
Copy link
Author

bradly commented Apr 26, 2013

Usage:

Settings.some_setting
Settings.some_setting = 'new_value'
Settings.save!
Settings.update_attributes(params[:settings])
Settings.new #=> Raises error

@jeremy
Copy link

jeremy commented Apr 26, 2013

Could assign the instance to a constant:

class SettingsSingleton < ActiveRecord::Base
  self.table_name = 'settings'
end

Settings = SettingsSingleton.first_or_create!

@bradly
Copy link
Author

bradly commented Apr 27, 2013

@jeremy:
Mind blown!
Thanks for that nugget!

Final code:

class SettingsSingleton < ActiveRecord::Base
  self.table_name = 'settings'
end

Settings = SettingsSingleton.first_or_create!

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment