Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Attempt to look up non-existing settings in parent classes (see #21) #55

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Copy link
Contributor

Choose a reason for hiding this comment

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

I'm curious. Why the respond_to??

{}.respond_to?(:default_proc) # => true

Copy link
Author

Choose a reason for hiding this comment

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

I took a clue from the argument name (obj). Because Cuba.deepclone is part of the public API, this patch could break code that calls Cuba.deepclone with anything other than a Hash.

Copy link
Contributor

Choose a reason for hiding this comment

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

Nice. Thanks for replying :-)

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