Skip to content

Instantly share code, notes, and snippets.

@TheNaoX
Created August 3, 2012 22:12
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 TheNaoX/3252043 to your computer and use it in GitHub Desktop.
Save TheNaoX/3252043 to your computer and use it in GitHub Desktop.
This model allows you to manipulate your variables as Setting.apple = {:color => "red", :taste => "sweet"}, and fetch data like this Setting.apple.color # => 'red'
require 'ostruct'
class Setting < ActiveRecord::Base
class SettingNotFound < RuntimeError ; end
validates_uniqueness_of :key
serialize :value
class << self
attr_accessor :data
def method_missing(mid, *args) # :nodoc:
mname = mid.id2name
len = args.length
if mname.chomp!('=')
if len != 1
raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
end
unless args[0].class == Hash
data[mname.to_sym] = args[0]
create( :s_type => args[0].class.to_s, :key => mname.to_sym, :value => args[0] )
else
value = OpenStruct.new args[0]
data[mname.to_sym] = value
create( :s_type => args[0].class.to_s, :key => mname.to_sym, :value => value )
end
elsif len == 0 and !!data[mid]
data[mid]
else
raise NoMethodError, "undefined method `#{mname}' for #{self}", caller(1)
end
end
def data
@data if @data
@data ||= refresh!
end
def refresh!
info = {}
find_each do |s|
info[s.key.to_sym] = s.value
end
info
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment