Skip to content

Commit

Permalink
Attempt to look up non-existing settings in parent classes (see sover…
Browse files Browse the repository at this point in the history
…an#21)

This fixes an issue where settings are added to Cuba.settings *after* inheriting
from `Cuba` are not picked up by the child classes. The problem is described in
issue soveran#21.

If a setting does not exist, Settings are looked up in the settings Hash of the parent class using `Hash#default_proc`. The settings Hash is still deepcloned, so
settings are still overridable.
  • Loading branch information
britishtea committed Dec 3, 2014
1 parent 40b21c8 commit f18f60f
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
17 changes: 16 additions & 1 deletion lib/cuba.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,26 @@ def self.settings
end

def self.deepclone(obj)
Marshal.load(Marshal.dump(obj))
# Hashes with a default_proc cannot be serialized by Marshal.dump.
if obj.respond_to?(:default_proc)
proc = obj.default_proc
obj.default_proc = nil
end

new_obj = Marshal.load(Marshal.dump(obj))

if obj.respond_to?(:default_proc)
obj.default_proc = proc
end

new_obj
end

def self.inherited(child)
child.settings.replace(deepclone(settings))
child.settings.default_proc = proc do |hash,key|
hash[key] = self.settings[key]
end
end

attr :env
Expand Down
16 changes: 16 additions & 0 deletions test/settings.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,22 @@ class Admin < Cuba; end
assert_equal "baz", Admin.settings[:foo]
end

test "attempts to get absent settings from parent class" do
class User < Cuba; end
class PowerUser < User; end

Cuba.settings[:get_from_parent] = "x"

assert_equal nil, Cuba.settings[:does_not_exist]
assert_equal nil, User.settings[:absent]
assert_equal "x", User.settings[:get_from_parent]
assert_equal "x", PowerUser.settings[:get_from_parent]

Cuba.settings[:after_deepcloning] = "x"

assert_equal "x", User.settings[:after_deepcloning]
end

test do
Cuba.settings[:hello] = "Hello World"

Expand Down

1 comment on commit f18f60f

@frodsan
Copy link

@frodsan frodsan commented on f18f60f Oct 5, 2015

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

Please sign in to comment.