dry-rb / dry-inflector

Inflector for Ruby
https://dry-rb.org/gems/dry-inflector
MIT License
95 stars 15 forks source link

:camelize_lower method produces unexpected result on acronyms #48

Open htcarr3 opened 1 year ago

htcarr3 commented 1 year ago

Describe the bug

When trying to camelize_lower a string with a known acronym like 'API', Dry::Inflector instance resolves to camelize_upper.

To Reproduce

require 'dry/inflector' inflector = Dry::Inflector.new inflector.camelize_lower('api-key') => "APIKey" inflector.camelize_lower('api') => "API" inflector.camelize_lower('key-api') => "keyAPI"

Expected behavior

My expectation would be that camelize_lower would default to the downcase spelling of the acronym inflector.camelize_lower('api-key') => "apiKey" inflector.camelize_lower('api') => "api"

My environment

Ruby 3.1.2, MacOS Ventura 13.4.1

htcarr3 commented 1 year ago

Maybe something like this?

# acronyms.rb
def apply_to(word, capitalize: true)
  if capitalize
    @rules[word.downcase] || word.capitalize
  else
    word
  end
end

or as a one-liner

# acronyms.rb
def apply_to(word, capitalize: true)
  capitalize ? (@rules[word.downcase] || word.capitalize) : word
end

camelize_lower "api-api" => "apiAPI"

Happy to open a PR if this makes sense.

htcarr3 commented 1 year ago

This does break the expectation on these tests, but I guess my question here is, aren't they strange assumptions on lower camelcase? The last two seem especially strange, I'm not sure I would expect someone to purposely lower_camelize a string that they, essentially, want to classify.

# camelize_lower_spec.rb
it "handles acronyms" do
  expect(subject.camelize_lower(i("json"))).to eql("JSON")
  expect(subject.camelize_lower(i("http_error"))).to eql("HTTPError")
  expect(subject.camelize_lower(i("openssl/hmac"))).to eql("OpenSSL::HMAC")
  expect(subject.camelize_lower(i("openssl/digest"))).to eql("OpenSSL::Digest")
end