Skip to content

Commit

Permalink
Improve naming of Ruby constants: convert unacceptable characters to …
Browse files Browse the repository at this point in the history
…'_' rather than omit them.
  • Loading branch information
Chris Andreae committed Jun 12, 2015
1 parent 84b4abd commit 7014d35
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/persistent_enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def cache_constants(model, required_constants, name_attr: :name)
# Set each value as a constant on this class. If reloading, only update if
# it's changed.
to_constant_name = ->(s){
value = s.strip.gsub(/[^\w\s-]/, '').underscore
value = s.strip.gsub(/[^\w\s-]/, '_').underscore
return nil if value.blank?
value.gsub!(/\s+/, '_')
value.gsub!(/_{2,}/, '_')
Expand Down
2 changes: 1 addition & 1 deletion lib/persistent_enum/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module PersistentEnum
VERSION = "1.0.7"
VERSION = "1.0.8"
end
19 changes: 19 additions & 0 deletions test/unit/persistent_enum_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,25 @@ def test_requires_constants
destroy_test_model(:test_requires_constant)
end

def test_constant_naming
test_constants = {
"CamelCase" => "CAMEL_CASE",
:Symbolic => "SYMBOLIC",
"with.punctuation" => "WITH_PUNCTUATION",
"multiple_.underscores" => "MULTIPLE_UNDERSCORES"
}

create_test_model(:test_constant_name, ->(t){ t.string :name }) do
PersistentEnum.cache_constants(self, test_constants.keys)
end

test_constants.each do |k, v|
assert_present(TestConstantName.const_get(v))
end

destroy_test_model(:test_constant_name)
end

def test_enum_immutable
assert_raises(ActiveRecord::ReadOnlyRecord) do
TestPersistentEnum.create(name: "foo")
Expand Down

0 comments on commit 7014d35

Please sign in to comment.