Permalink
Browse files

Assignment of configuration with []= and method missing

  • Loading branch information...
1 parent 3033156 commit 7894c71e294b58b9872480de7cf2e387919766aa @jnicklas jnicklas committed Mar 22, 2011
Showing with 42 additions and 2 deletions.
  1. +15 −2 app/models/configurable.rb
  2. +27 −0 dummy/spec/models/configurable_spec.rb
View
@@ -14,6 +14,15 @@ def self.keys
self.defaults.collect { |k,v| k.to_s }.sort
end
+ def self.[]=(key, value)
+ exisiting = find_by_name(key)
+ if exisiting
+ exisiting.update_attribute(:value, value)
+ else
+ create(:name => key.to_s, :value => value)
+ end
+ end
+
def self.[](key)
value = find_by_name(key).try(:value) || self.defaults[key][:default]
case self.defaults[key][:type]
@@ -32,9 +41,13 @@ def self.[](key)
end
def self.method_missing(name, *args)
- name_stripped = name.to_s.gsub('?', '')
+ name_stripped = name.to_s.sub(/[\?=]$/, '')
if self.keys.include?(name_stripped)
- self[name_stripped]
+ if name.to_s.end_with?('=')
+ self[name_stripped] = args.first
+ else
+ self[name_stripped]
+ end
else
super
end
@@ -24,6 +24,28 @@
end
end
+ describe ".[]=" do
+ context "with no saved value" do
+ it "creates a new entry" do
+ Configurable[:notify_email] = "john@example.com"
+ Configurable.find_by_name('notify_email').value.should == 'john@example.com'
+ Configurable.count.should == 1
+ end
+ end
+
+ context "with a saved value" do
+ before do
+ Configurable.create!(:name => 'notify_email', :value => 'paul@rslw.com')
+ end
+
+ it "updates the existing value" do
+ Configurable[:notify_email] = "john@example.com"
+ Configurable.find_by_name('notify_email').value.should == 'john@example.com'
+ Configurable.count.should == 1
+ end
+ end
+ end
+
describe ".[]" do
context "with no saved value" do
it "shoud pick up the default value" do
@@ -102,6 +124,11 @@
it "should return the correct value" do
Configurable.notify_email.should == 'mreider@engineyard.com'
end
+
+ it "should assign the correct value" do
+ Configurable.notify_email = 'john@example.com'
+ Configurable.notify_email.should == 'john@example.com'
+ end
end
end

0 comments on commit 7894c71

Please sign in to comment.