Skip to content

Instantly share code, notes, and snippets.

@elskwid
Last active August 29, 2015 14:10
Show Gist options
  • Save elskwid/236b57298b5b29777e9f to your computer and use it in GitHub Desktop.
Save elskwid/236b57298b5b29777e9f to your computer and use it in GitHub Desktop.
Mustache .const_get! for locks
# Little work for the const_get functionality in Mustache for @locks
require "minitest/autorun"
module Single
end
module Nested
module Nested
module Deep
end
end
module AlsoNested
end
end
class ConstGetTest < Minitest::Test
class A
# simplified because of the inherit parameter
def self.const_get!(module_path)
if const_defined?(module_path, true)
const_get(module_path, true)
else
nil # I don't think this is needed: Object.const_missing(module_path)
end
rescue NameError
nil
end
def self.old_const_get!(module_path)
module_path.split('::').inject(Object) do |mod, name|
next Object if name.empty?
if mod.const_defined?(name, false)
mod.const_get(name)
else
mod.const_missing(name)
end
end
rescue NameError
nil
end
end
def test_top_level_module_Single
assert_equal Single, A.const_get!("Single")
end
def test_top_level_module_Nested
assert_equal Nested, A.const_get!("Nested")
end
def test_top_level_module_Missing
assert_equal nil, A.const_get!("Missing")
end
def test_top_level_with_colons
assert_equal Single, A.const_get!("::Single")
end
def test_nested_with_same_name
assert_equal Nested::Nested, A.const_get!("Nested::Nested")
end
def test_missing_nested_with_same_name
assert_equal nil, A.const_get!("Nested::Nested::Nested")
end
def test_nested_module_same_parent
assert_equal Nested::AlsoNested, A.const_get!("Nested::AlsoNested")
end
def test_deep_nested_module
assert_equal Nested::Nested::Deep, A.const_get!("Nested::Nested::Deep")
end
end
:~/mustache$ ruby const_get.rb
Run options: --seed 23678
# Running:
........
Finished in 0.001681s, 4758.0417 runs/s, 4758.0417 assertions/s.
8 runs, 8 assertions, 0 failures, 0 errors, 0 skips
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment