Rails article helper - "a" or "an"
Does anyone know of a Rails Helper which can automatica开发者_如何学JAVAlly prepend the appropriate article to a given string? For instance, if I pass in "apple" to the function it would turn out "an apple", whereas if I were to send in "banana" it would return "a banana"
I already checked the Rails TextHelper module but could not find anything. Apologies if this is a duplicate but it is admittedly a hard answer to search for...
None that I know of but it seems simple enough to write a helper for this right? Off the top of my head
def indefinite_articlerize(params_word)
%w(a e i o u).include?(params_word[0].downcase) ? "an #{params_word}" : "a #{params_word}"
end
hope that helps
edit 1: Also found this thread with a patch that might help you bulletproof this more https://rails.lighthouseapp.com/projects/8994/tickets/2566-add-aan-inflector-indefinitize
There is now a gem for this: indefinite_article.
Seems like checking that the first letter is a vowel would get you most of the way there, but there are edge cases:
- Some people will say "an historic moment" but write "a historic moment".
- But, it's "a history"!
- Acronyms and abbreviations are problematic ("An NBC reporter" but "A NATO authority")
- Words starting with a vowel but pronounced with an initial consonant ("a union")
- Others?
(source)
I know the following answer goes too much for a practical simple implementation, but in case someone wants to do it with accuracy under some scale of implementation.
The rule is actually pretty much simple, but the problem is that the rule is dependent on the pronounciation, not spelling:
If the initial sound is a vowel sound (not necessarily a vowel letter), then prepend 'an', otherwise prepend 'a'.
Referring to John's examples:
'an hour' because the 'h' here is a vowel sound, whereas 'a historic' because the 'h' here is a consonant sound. 'an NBC' because the 'N' here is read as 'en', whereas 'a NATO' because the 'N' here is read as 'n'.
So the question is reduced to finding out: "when are certain letters pronounced as vowel sounds". In order to do that, you somehow need to access a dictionary that has phonological representations for each word, and check its initial phoneme.
Look into https://deveiate.org/code/linguistics/ - it provides handling of indefinite articles and much more. I've used it successfully on many projects.
I love the gem if you want a comprehensive solution. But if you just want tests to read more nicely, it is helpful to monkey patch String to follow the standard Rails inflector pattern:
class String
def articleize
%w(a e i o u).include?(self[0].downcase) ? "an #{self}" : "a #{self}"
end
end
精彩评论