Posted 4 months ago. Visible to the public.

Unpoly: Testing values for presence or blankness

In Ruby on Rails, all objects have a useful blank? method. It returns true for nil but also for empty strings or empty arrays. There is also a universal method present? which returns true for all values that are not blank?.

In JavaScript you need to roll your own implementation of blank? and present?.

If your application uses Unpoly you may also use up.util.isBlank(). By default, this function returns true for:

  • undefined
  • null
  • Empty strings
  • Empty arrays
  • A plain object without own enumerable properties

All other arguments return false.

There is also a function up.util.isPresent(), which returns the opposite of up.util.isBlank().

Defining blankness for custom types

Your application might define a custom class (like VideoList) for which you might want to define your own concept of "blankness". To do so, have your class implement a method named up.util.isBlank.key and up.util.isBlank() will use this method to determine blankness.

Example

We have a user-defined Account class that we want to use with up.util.isBlank():

Copy
class Account { constructor(email) { this.email = email } [up.util.isBlank.key]() { return up.util.isBlank(this.email) } }

Note that the protocol method is not actually named 'up.util.isBlank.key'. Instead it is named after the value of the up.util.isBlank.key property. To do so, the code sample above is using a computed property name in square brackets.

We may now use Account instances with up.util.isBlank():

Copy
foo = new Account('foo@foo.com') bar = new Account('') console.log(up.util.isBlank(foo)) // prints false console.log(up.util.isBlank(bar)) // prints true

Testing for missing values

JavaScript has both undefined or null to represent a missing value. Although there used to be a separate use case for both, the distinction is one of such fine subtlety that today's APIs are arbitrarily using one or the other.

If your code does not care about the distinction, you may use up.util.isMissing(), which returns true for both. The opposite is up.util.isGiven().

makandra has been working exclusively with Ruby on Rails since 2007. Our laser focus on a single technology has made us a leader in this space.

Owner of this card:

Avatar
Henning Koch
Last edit:
4 months ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more