How to check for empty brackets in a string?

Let’s say we have a Movie model with “title” attribute and we would like to validate the title for empty brackets. For example:

“Some text some text (some text) some text some text” #=> Valid title
“Some text some text [some text] some text some text” #=> Valid title
“Some text some text {some text} some text some text” #=> Valid title

“Some text some text () some text some text” #=> Invalid title
“Some text some text [] some text some text” #=> Invalid title
“Some text some text {} some text some text” #=> Invalid title

Let’s first implement a way to validate the string for empty brackets.

def is_valid_string(string)
  %w[ () [] {} ].none?(&string.method(:include?))
end

What happens here is I create an empty array of empty brackets and parenthesis which I will use when iterating over each of the characters in the string. Next, I use none? which accepts a block. In the block I call each on each of the elements in the array of brackets. The most interesting and probably confusing parts is that each accepts either an explicit block or proc. The proc. string.method(:include?) returns a method include defined on String instance string and & converts it to proc.

Let’s now implement this validation into our Movie model.
Raisl offers plenty of validations out of the box, such as “presence”, “uniqness”, “numericality”, and so on. What if we want to have our own validations? Rails allows us to create our custom validations as well.

A custom validator is a class that inherits from ActiveModel::Validator. This class must implement the validate method which takes a record as an argument and performs the validation on it. The custom validator is called using the validates_with method. Let’s move our method into a new class called TitleBracketsValidator, then, and use it within our Movie model.

class TitleBracketsValidator < ActiveModel::Validator
  def validate(record)
    string = record.title

    if !is_valid_string(string)
      record.errors.add(string, "brackets cannot be empty")
    end
  end

  def is_valid_string(string)
    %w[ () [] {} ].none?(&string.method(:include?))
  end
end

class Movie < ApplicationRecord
  validates_with TitleBracketsValidator
end

That’s it.
Thank you for reading and stay tuned for more.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s