Created
April 26, 2013 17:28
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Settings < ActiveRecord::Base | |
include ActiveRecordSingleton | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@jeremy:

Thanks for that nugget!
Final code: