-
-
Save andiskiy/aa1a6e3493739aaba8836bc7ce88a5c9 to your computer and use it in GitHub Desktop.
Rails Singleton Model
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 CreateSettings < ActiveRecord::Migration | |
def change | |
create_table :settings do |t| | |
t.integer :singleton_guard | |
t.string :setting_1 | |
t.integer :setting_2 | |
t.timestamps null: false | |
end | |
add_index(:settings, :singleton_guard, :unique => true) | |
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
Rails Singleton Model | |
Taken from: | |
http://stackoverflow.com/questions/399447/how-to-implement-a-singleton-model/12463209#12463209 |
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 | |
# The "singleton_guard" column is a unique column which must always be set to '0' | |
# This ensures that only one AppSettings row is created | |
validates :singleton_guard, inclusion: { in: [0] } | |
def self.instance | |
# there will be only one row, and its ID must be '1' | |
begin | |
find(1) | |
rescue ActiveRecord::RecordNotFound | |
# slight race condition here, but it will only happen once | |
row = Settings.new | |
row.singleton_guard = 0 | |
row.save! | |
row | |
end | |
end | |
def self.method_missing(method, *args) | |
if Settings.instance.methods.include?(method) | |
Settings.instance.send(method, *args) | |
else | |
super | |
end | |
end | |
# Validations | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment