Skip to content

Commit 62a4885

Browse files
committed
fix: symbol lookup without Rails
1 parent 8145537 commit 62a4885

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# frozen_string_literal: true
2+
3+
module ActionPolicy
4+
module Ext
5+
# Add `classify` to Symbol
6+
module SymbolClassify
7+
refine Symbol do
8+
if "".respond_to?(:classify)
9+
def classify
10+
to_s.classify
11+
end
12+
else
13+
def classify
14+
word = to_s.capitalize
15+
word.gsub!(/(?:_)([a-z\d]*)/) { $1.capitalize }
16+
word
17+
end
18+
end
19+
end
20+
end
21+
end
22+
end

lib/action_policy/lookup_chain.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,9 @@ module LookupChain
1212
using ActionPolicy::Ext::StringConstantize
1313
end
1414

15+
require "action_policy/ext/symbol_classify"
16+
using ActionPolicy::Ext::SymbolClassify
17+
1518
require "action_policy/ext/module_namespace"
1619
using ActionPolicy::Ext::ModuleNamespace
1720

@@ -111,7 +114,7 @@ def policy_class_name_for(record)
111114
SYMBOL_LOOKUP = ->(record, namespace: nil, **) {
112115
next unless record.is_a?(Symbol)
113116

114-
policy_name = "#{record.to_s.classify}Policy"
117+
policy_name = "#{record.classify}Policy"
115118
if namespace.nil?
116119
policy_name.safe_constantize
117120
else
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# frozen_string_literal: true
2+
3+
require "test_helper"
4+
5+
require "action_policy/ext/symbol_classify"
6+
using ActionPolicy::Ext::SymbolClassify
7+
8+
class TestSymbolClassify < Minitest::Test
9+
def test_simple_name
10+
assert_equal "Test", :test.classify
11+
end
12+
13+
def test_underscored_name
14+
assert_equal "TeStO", :te_st_o.classify
15+
end
16+
end

0 commit comments

Comments
 (0)