Skip to content

Commit ba40b98

Browse files
committed
Create ActiveMethod::Util
1 parent 7e9aa52 commit ba40b98

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

lib/active_method/util.rb

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
module ActiveMethod
2+
module Util
3+
module_function
4+
5+
def constantize(klass, name)
6+
constant = klass.const_get(name) rescue nil
7+
return constant unless constant.nil?
8+
9+
namespaces_of(klass).each do |namespace|
10+
constant = namespace.const_get(name) rescue nil
11+
return constant unless constant.nil?
12+
end
13+
14+
raise NameError.new("wrong constant name #{name}") if constant.nil?
15+
end
16+
17+
def namespaces_of(klass)
18+
namespaces = []
19+
20+
names = klass.name.split("::")
21+
names.pop
22+
while !names.empty?
23+
namespaces << Object.const_get(names.join("::"))
24+
names.pop
25+
end
26+
27+
namespaces
28+
end
29+
30+
def camel_case(str)
31+
str = str.to_s
32+
return str if str !~ /_/ && str =~ /[A-Z]+.*/
33+
str.split("_").map(&:capitalize).join
34+
end
35+
36+
def snake_case(str)
37+
return str.downcase if str =~ /^[A-Z_]+$/
38+
str.gsub(/\B[A-Z]/, '_\&').squeeze("_") =~ /_*(.*)/
39+
$+.downcase
40+
end
41+
42+
end
43+
end

test/active_method/test_util.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# frozen_string_literal: true
2+
3+
require "test_helper"
4+
5+
class TestUtil < ApplicationTest
6+
7+
it "constantize - raise error on missing constant" do
8+
error = assert_raises NameError do
9+
ActiveMethod::Util.constantize(Object, 'WrongName')
10+
end
11+
12+
assert_includes error.message, "wrong constant name WrongName"
13+
end
14+
15+
end

0 commit comments

Comments
 (0)