Coder Social home page Coder Social logo

inflected's Introduction

inflected

Travis build status npm downloads no dependencies license

A port of ActiveSupport's inflector to Node.js. Also usable in the browser.

Installation

Install via npm:

% npm install inflected

Or via yarn:

% yarn add inflected

The UMD build is also available on unpkg, adding a Inflector object to the global scope.

<script src="https://unpkg.com/inflected/dist/umd/inflected.min.js"></script>

Usage

The module exports an object with several utility functions.

var Inflector = require('inflected');

Inflector.pluralize('Category')  // => 'Categories'

If using ES modules, you can cherry-pick only the functions you're interested in:

import { pluralize } from 'inflected';

pluralize('Category')  // => 'Categories'

Here is the complete API reference:

Inflector.pluralize

string pluralize(string word[, string locale])

Returns the plural form of the word in the string.

If passed an optional locale parameter, the word will be pluralized using rules defined for that language. By default, this parameter is set to "en".

Inflector.pluralize('post')          // => 'posts'
Inflector.pluralize('octopus')       // => 'octopi'
Inflector.pluralize('sheep')         // => 'sheep'
Inflector.pluralize('words')         // => 'words'
Inflector.pluralize('CamelOctopus')  // => 'CamelOctopi'
Inflector.pluralize('ley', 'es')     // => 'leyes'

Inflector.singularize

string singularize(string word[, string locale])

The reverse of pluralize, returns the singular form of a word in a string.

If passed an optional locale parameter, the word will be singularized using rules defined for that language. By default, this parameter is set to "en".

Inflector.singularize('posts')        // => 'post'
Inflector.singularize('octopi')       // => 'octopus'
Inflector.singularize('sheep')        // => 'sheep'
Inflector.singularize('word')         // => 'word'
Inflector.singularize('CamelOctopi')  // => 'CamelOctopus'
Inflector.singularize('leyes', 'es')  // => 'ley'

Inflector.camelize

string camelize(string term[, boolean uppercaseFirstLetter])

By default, camelize converts strings to UpperCamelCase. If the second argument is set to false then camelize produces lowerCamelCase.

Inflector.camelize('foo_bar')         // => 'FooBar'
Inflector.camelize('foo_bar', false)  // => 'fooBar'

As a rule of thumb you can think of camelize as the inverse of underscore, though there are cases where that does not hold:

Inflector.camelize(Inflector.underscore('SSLError'))  // => 'SslError'

Inflector.underscore

string underscore(string camelCasedWord)

Makes an underscored, lowercase form from the expression in the string.

Inflector.underscore('FooBar')  // => 'foo_bar'

As a rule of thumb you can think of underscore as the inverse of camelize, though there are cases where that does not hold:

Inflector.camelize(Inflector.underscore('SSLError'))  // => 'SslError'

Inflector.humanize

string humanize(string lowerCaseAndUnderscoredWord[, object options])

Capitalizes the first word, turns underscores into spaces, and strips a trailing "_id" if present.

Like titleize, this is meant for creating pretty output.

The capitalization of the first word can be turned off by setting the capitalize option key to false. By default, this option is true.

Inflector.humanize('employee_salary')                   // => 'Employee salary'
Inflector.humanize('author_id')                         // => 'Author'
Inflector.humanize('author_id', { capitalize: false })  // => 'author'

Inflector.titleize

string titleize(string sentence)

Capitalizes all the words and replaces some characters in the string to create a nicer looking title. titleize is meant for creating pretty output.

Inflector.titleize('man from the boondocks')   // => 'Man From The Boondocks'
Inflector.titleize('x-men: the last stand')    // => 'X Men: The Last Stand'
Inflector.titleize('TheManWithoutAPast')       // => 'The Man Without A Past'
Inflector.titleize('raiders_of_the_lost_ark')  // => 'Raiders Of The Lost Ark'

Inflector.tableize

string tableize(string className)

Create the name of a table like Rails does for models to table names. This method uses the pluralize method on the last word in the string.

Inflector.tableize('RawScaledScorer')  // => 'raw_scaled_scorers'
Inflector.tableize('egg_and_ham')      // => 'egg_and_hams'
Inflector.tableize('fancyCategory')    // => 'fancy_categories'

Inflector.classify

string classify(string tableName)

Create a class name from a plural table name like Rails does for table names to models.

Inflector.classify('egg_and_hams')  // => 'EggAndHam'
Inflector.classify('posts')         // => 'Post'

Singular names are not handled correctly:

Inflector.classify('business')  // => 'Busines'

Inflector.dasherize

string dasherize(string underscoredWord)

Replaces underscores with dashes in the string.

Inflector.dasherize('puni_puni')  // => 'puni-puni'

Inflector.foreignKey

string foreignKey(string className[, boolean separateClassNameAndIdWithUnderscore])

Creates a foreign key name from a class name. separateClassNameAndIdWithUnderscore sets whether the method should put "_" between the name and "id" (default: true).

Inflector.foreignKey('Message')         // => 'message_id'
Inflector.foreignKey('Message', false)  // => 'messageid'

Inflector.ordinal

string ordinal(object number)

Returns the suffix that should be added to a number to denote the position in an ordered sequence such as 1st, 2nd, 3rd, 4th.

Inflector.ordinal(1)      // => 'st'
Inflector.ordinal(2)      // => 'nd'
Inflector.ordinal(1002)   // => 'nd'
Inflector.ordinal(1003)   // => 'rd'
Inflector.ordinal(-11)    // => 'th'
Inflector.ordinal(-1021)  // => 'st'

Inflector.ordinalize

string ordinalize(object number)

Turns a number into an ordinal string used to denote the position in an ordered sequence such as 1st, 2nd, 3rd, 4th.

Inflector.ordinalize(1)      // => '1st'
Inflector.ordinalize(2)      // => '2nd'
Inflector.ordinalize(1002)   // => '1002nd'
Inflector.ordinalize(1003)   // => '1003rd'
Inflector.ordinalize(-11)    // => '-11th'
Inflector.ordinalize(-1021)  // => '-1021st'

Inflector.inflections

Inflections inflections([string locale])
inflections([string locale], [function(Inflections) fn])

A singleton instance of the internal Inflections class is yielded by this function, which can then be used to specify additional inflection rules. If passed an optional locale, rules for other languages can be specified. The default locale is "en". Only rules for English are provided by this library.

Inflector.inflections('en', function(inflect) {
  inflect.plural(/^(ox)$/i, '$1$2en');
  inflect.singular /^(ox)en/i, '$1');

  inflect.irregular('octopus', 'octopi');

  inflect.uncountable('equipment', 'snow');
});

New rules are added at the top. So in the example above, the irregular rule for octopus will now be the first of the pluralization and singularization rules that is run. This guarantees that your rules run before any of the rules that may already have been loaded.

Inflector.transliterate

string transliterate(string sentence[, object options])

Replaces non-ASCII characters with an ASCII approximation, or if none exists, a replacement character which defaults to "?".

Inflector.transliterate('Ærøskøbing')  // => 'AEroskobing'

Default approximations are provided for Western/Latin characters, e.g, "ø", "ñ", "é", "ß", etc.

This method is I18n-aware, so you can set up custom approximations for a locale. This can be useful, for example, to transliterate German's "ü" and "ö" to "ue" and "oe", or to add support for transliterating Russian to ASCII.

In order to make your custom transliterations available, you must set them using the approximate helper function:

Inflector.transliterations('de', function(t) {
  t.approximate('ü', 'ue');
  t.approximate('ö', 'oe');
});

Now you can have different transliterations for each locale:

Inflector.transliterate('Jürgen')                    // => 'Jurgen'
Inflector.transliterate('Jürgen', { locale: 'de' })  // => 'Juergen'

Inflector.parameterize

string parameterize(string sentence[, object options])

Replaces special characters in a string so that it may be used as part of a 'pretty' URL.

Inflector.parameterize('Donald E. Knuth')                      // => 'donald-e-knuth'
Inflector.parameterize('Donald E. Knuth', { separator: '+' })  // => 'donald+e+knuth'

As of v2.1, there's also a preserveCase option:

Inflector.parameterize('Donald E. Knuth', { preserveCase: true })  // => 'Donald-E-Knuth'

Inflector.constantify

string constantify(string words)

Converts words (camelCased, under_scored, or dasherized) to CONSTANT_CASE.

Inflector.constantify('bankAccount')   // => 'BANK_ACCOUNT'
Inflector.constantify('bank-account')  // => 'BANK_ACCOUNT'
Inflector.constantify('bank_account')  // => 'BANK_ACCOUNT'
Inflector.constantify('Bank Account')  // => 'BANK_ACCOUNT'

Contributing

Here's a quick guide:

  1. Fork the repo and make install.
  2. Run the tests. We only take pull requests with passing tests, and it's great to know that you have a clean slate: make test.
  3. Add a test for your change. Only refactoring and documentation changes require no new tests. If you are adding functionality or are fixing a bug, we need a test!
  4. Make the test pass.
  5. Push to your fork and submit a pull request.

Licence

Released under The MIT License.

inflected's People

Contributors

dakolech avatar davidonlaptop avatar dependabot[bot] avatar jeremypearson avatar martinandert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

inflected's Issues

Spanish inflector not working

var Inflector = require('inflected');

console.log(Inflector.singularize('arroces', 'es'));
console.log(Inflector.singularize('autos', 'es'));
console.log(Inflector.singularize('veganos', 'es'));

Outputs the same input!

Usage of `char` as a variable name should be avoided

char is on the list of reserved words and should be avoided in general.

Specifically, I'm running into the issue as part of browserifying/webpacking a project with es3ify, which replaces dot accessed reserved words that are now part of the API with bracket references.

DEFAULT_APPROXIMATIONS[char]) is replaced as DEFAULT_APPROXIMATIONS["char"])

I think es3ify is being a little overzealous here and I'll report an issue there as well but it would be nice to just not use a "reserved" word.

Singular of "delta" is not correct

Hi,

I've been using your library as a dependency of MirageJS. We had a pretty nasty bug in our models where the singularize method is returning deltum as the singular of the word delta.

You can try it with:

Inflector.singularize('delta')

Cannot read property 'underscore' of undefined

Using v2.0.1, I do this:

import {titleize} from 'inflected';
titleize('foo_bar');

And get this error.

Uncaught TypeError: Cannot read property 'underscore' of undefined
    at titleize (inflected.js:389)

Add Constantize Feature

Good work guys!

ActiveSupport has a constantize method that turns an input into a CONSTANT_CASE.

If you're interested in the feature, I can look if I find time to contribute it.

parameterize default separator does not match ActiveSupport

Hey there fellow Rubyist, thanks for making this available. I noticed a difference in the way inflected handles parameterize on strings, specifically the separator.

ActiveSupport parameterize
https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize
parameterize(string, separator: "-", preserve_case: false)

inflected parameterize
parameterize(string, separator: "")

Example string is the name of a pet from World of Warcraft: Lil' Ben'fon

ActiveSupport parameterize:

"Lil' Ben'fon".parameterize
=> "lil-ben-fon"

inflected parameterize

parameterize("Lil' Ben'fon")
=> `lil-benfon`

Trying to get in touch regarding a security issue

Hey there!

I'd like to report a security issue but cannot find contact instructions on your repository.

If not a hassle, might you kindly add a SECURITY.md file with an email, or another contact method? GitHub recommends this best practice to ensure security issues are responsibly disclosed, and it would serve as a simple instruction for security researchers in the future.

Thank you for your consideration, and I look forward to hearing from you!

(cc @huntr-helper)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.