Search code examples
rubysequel

What tools are available for value normalization in Rails and Sequel?


I'm using Rails 4 with Sequel for my ORM. I would like to do some basic normalization on incoming values, such as making casing consistent (Male to male) and mapping to canonical values (USA to US). Where should I be doing this? Does Sequel provide value normalization hooks? Or should I be doing it in the Rails controller?

I am currently using the around_save Sequel::Model hook, but the Sequel documentation doesn't discuss value normalization so I'm not sure if this is a good place to do it.

class People < Sequel::Model
  def before_save
    normalize_gender
    super
  end

  private
  def normalize_gender
    if self.gender.nil?
      self.gender = ''
      return;
    end

    self.gender.downcase!

    self.gender = 'male'   if self.gender == 'm'
    self.gender = 'female' if self.gender == 'f'

    return
  end
end

I'm familiar with MVC, but not with Rails and Sequel specifically. I'm looking for what existing hooks and techniques are available in these tools, not a general discussion of where value normalization should be done.


Solution

  • You probably want to use the Sequel input_transformer plugin: http://sequel.jeremyevans.net/rdoc-plugins/classes/Sequel/Plugins/InputTransformer.html