All Projects → mdeering → Attribute_normalizer

mdeering / Attribute_normalizer

Licence: mit
Adds the ability to normalize attributes cleanly with code blocks and predefined normalizers

Programming Languages

ruby
36898 projects - #4 most used programming language

Projects that are alternatives of or similar to Attribute normalizer

Ar lazy preload
Lazy loading associations for the ActiveRecord models
Stars: ✭ 281 (-40.59%)
Mutual labels:  activerecord, rails
Strip attributes
🔪 An ActiveModel extension that automatically strips all attributes of leading and trailing whitespace before validation. If the attribute is blank, it strips the value to nil.
Stars: ✭ 441 (-6.77%)
Mutual labels:  activerecord, rails
Pg party
ActiveRecord PostgreSQL Partitioning
Stars: ✭ 294 (-37.84%)
Mutual labels:  activerecord, rails
Public activity
Easy activity tracking for models - similar to Github's Public Activity
Stars: ✭ 2,822 (+496.62%)
Mutual labels:  activerecord, rails
Activerecord Jdbc Adapter
JRuby's ActiveRecord adapter using JDBC.
Stars: ✭ 457 (-3.38%)
Mutual labels:  activerecord, rails
Elasticsearch Rails
Elasticsearch integrations for ActiveModel/Record and Ruby on Rails
Stars: ✭ 2,896 (+512.26%)
Mutual labels:  activerecord, rails
Algoliasearch Rails
AlgoliaSearch integration to your favorite ORM
Stars: ✭ 352 (-25.58%)
Mutual labels:  activerecord, rails
Seamless database pool
Add support for master/slave database clusters in ActiveRecord to improve performance.
Stars: ✭ 222 (-53.07%)
Mutual labels:  activerecord, rails
Second level cache
Write Through and Read Through caching library inspired by CacheMoney and cache_fu, support ActiveRecord 4, 5 and 6.
Stars: ✭ 380 (-19.66%)
Mutual labels:  activerecord, rails
Annotate models
Annotate Rails classes with schema and routes info
Stars: ✭ 3,849 (+713.74%)
Mutual labels:  activerecord, rails
Clowne
A flexible gem for cloning models
Stars: ✭ 260 (-45.03%)
Mutual labels:  activerecord, rails
Store model
Work with JSON-backed attributes as ActiveRecord-ish models
Stars: ✭ 410 (-13.32%)
Mutual labels:  activerecord, rails
Scenic
Scenic is maintained by Derek Prior, Caleb Hearth, and you, our contributors.
Stars: ✭ 2,856 (+503.81%)
Mutual labels:  activerecord, rails
Pluck to hash
Extend ActiveRecord pluck to return array of hashes
Stars: ✭ 275 (-41.86%)
Mutual labels:  activerecord, rails
Activerecord Postgres enum
Integrate PostgreSQL's enum data type into ActiveRecord's schema and migrations.
Stars: ✭ 227 (-52.01%)
Mutual labels:  activerecord, rails
Html5 validators
A gem/plugin for Rails 3, Rails 4, Rails 5, and Rails 6 that enables client-side validation using ActiveModel + HTML5 Form Validation
Stars: ✭ 302 (-36.15%)
Mutual labels:  activerecord, rails
Activerecord Turntable
ActiveRecord Sharding Plugin
Stars: ✭ 206 (-56.45%)
Mutual labels:  activerecord, rails
Secondbase
Seamless second database integration for Rails.
Stars: ✭ 216 (-54.33%)
Mutual labels:  activerecord, rails
Isolator
Detect non-atomic interactions within DB transactions
Stars: ✭ 362 (-23.47%)
Mutual labels:  activerecord, rails
Deep pluck
Allow you to pluck attributes from nested associations without loading a bunch of records.
Stars: ✭ 385 (-18.6%)
Mutual labels:  activerecord, rails

h1. Attribute Normalizer

!https://secure.travis-ci.org/mdeering/attribute_normalizer.png?branch=master(Build Status)!:http://travis-ci.org/mdeering/attribute_normalizer

p. A little normalization goes a long way in helping maintain data integrity.

h2. Change History

  • 1.1.0 ** Allow the use of default normalizers before and after the evaluation of a given block

  • 1.0.0 ** -DSL Changes- ** Default attributes to normalize ** mongid support

  • 0.3.0 ** Normalizer Chaining ** Built-in common normalizers ** Ability to change the default attribute normalization.

  • 0.2.1 ** ActiveModel Support Built-in ** Fix for :with option getting dropped when normalizing several attributes

  • 0.2.0 ** Removed the normalization on reads. ** Added out of the box support for CassandraObjects ** Included RSpec matcher normalizer_attribute ** Added the ability to define global normalizers ** Strings no longer get 'strip' called on them before getting passed on to your defined normalization blocks

h2. Supported ORMs

  • Active Model
  • Active Record
  • CassandraObjects

p. I will gladly take pull requests to automatically load Attribute Normalizer into your ORM of choice if requested. To test it out on your ORM just include the AttributeNormalizer module after requiring it.

# your_initializer.rb
require 'attribute_normalizer'
YourORM::Base.send :include, AttributeNormalizer

h2. Install

sudo gem install attribute_normalizer

p. Then just required it. Rails usages is as follows.

h3. Rails 2

# config/environment.rb
config.gem 'attribute_normalizer'

h3. Rails 3

# Gemfile
gem 'attribute_normalizer'

p. It also still works as a traditional Rails plugin.

./script/plugin install git://github.com/mdeering/attribute_normalizer.git

h2. Usage

p. Lets create a quick test/spec for what we want to accomplish as far as normalization using the built in RSpec matcher.

# spec/models/book_spec.rb
describe Book do
  it { should normalize_attribute(:author) }
  it { should normalize_attribute(:price).from('$3,450.98').to(3450.98) }
  it { should normalize_attribute(:summary).from('   Here is my summary that is a little to long   ').to('Here is m...') }
  it { should normalize_attribute(:title).from(' pick up chicks with magic tricks  ').to('Pick Up Chicks With Magic Tricks') }
  it { should normalize_attribute(:slug).from(' Social Life at the Edge of Chaos    ').to('social-life-at-the-edge-of-chaos') }
  it { should normalize_attribute(:limited_slug).from(' Social Life at the Edge of Chaos    ').to('social-life') }
end

p. The following normalizers are already included with the +0.3 version of the gem.

  • :blank Will return nil on empty strings
  • :phone Will strip out all non-digit characters and return nil on empty strings
  • :strip Will strip leading and trailing whitespace.
  • :squish Will strip leading and trailing whitespace and convert any consecutive spaces to one space each

p. And lets predefine some normalizers that we may use in other classes/models or that we don't want to clutter up our class/model's readability with.

# config/initializers/attribute_normalizer.rb
AttributeNormalizer.configure do |config|

  config.normalizers[:currency] = lambda do |value, options|
    value.is_a?(String) ? value.gsub(/[^0-9\.]+/, '') : value
  end

  config.normalizers[:truncate] = lambda do |text, options|
    if text.is_a?(String)
      options.reverse_merge!(:length => 30, :omission => "...")
      l = options[:length] - options[:omission].mb_chars.length
      chars = text.mb_chars
      (chars.length > options[:length] ? chars[0...l] + options[:omission] : text).to_s
    else
      text
    end
  end

  # The default normalizers if no :with option or block is given is to apply the :strip and :blank normalizers (in that order).
  # You can change this if you would like as follows:
  # config.default_normalizers = :strip, :blank

end

The normalize_attributes method is eager loaded into your ORM. normalize_attribute is aliased to normalize_attributes and both can take in a single attribute or an array of attributes.

class Book < ActiveRecord::Base

  # By default it will strip leading and trailing whitespace
  # and set to nil if blank.
  normalize_attributes :author, :publisher

  # Using one of our predefined normalizers.
  normalize_attribute  :price, :with => :currency

  # Using more then one of our predefined normalizers including one with options
  normalize_attribute :summary, :with => [ :strip, { :truncate => { :length => 12 } } ]

  # You can also define your normalization block inline.
  normalize_attribute :title do |value|
    value.is_a?(String) ? value.titleize.strip : value
  end

  # Or use a combination of normalizers plus an inline block.
  # the normalizers in the :with option will each be evalulated
  # in order and the result will be given to the block.
  # You could also use option :before in place of :with
  normalize_attribute :slug, :with => [ :strip, :blank ] do |value|
    value.present? && value.is_a?(String) ? value.downcase.gsub(/\s+/, '-') : value
  end

  # Use builtin normalizers before and after the evaluation of your inline
  # block
  normalize_attribute :limited_slug, :before => [ :strip, :blank ], :after => [ { :truncate => { :length => 11, :omission => '' } } ] do |value|
    value.present? && value.is_a?(String) ? value.downcase.gsub(/\s+/, '-') : value
  end

end

p. All the specs will pass now. Here is quick look at the behaviour from a console.

summary = 'Here is my summary that is a little to long'
title   = 'pick up chicks with magic tricks'
book    = Book.create!(:author => '', :price => '$3,450.89', :summary => summary, :title => title, :slug => title, :limited_slug => title)
book.author       # => nil
book.price        # => 3450.89
book.summary      # => 'Here is m...'
book.title        # => 'Pick Up Chicks With Magic Tricks'
book.slug         # => 'pick-up-chicks-with-magic-tricks'
book.limited_slug # => 'pick-up-chi'

h2. Test Helpers

p. If you are running RSpec there is a matcher available for use. Usage can been seen above. Include it as follows.

h3. Rails 2

# spec/spec_helper.rb
RSpec.configure do |config|
  config.include AttributeNormalizer::RSpecMatcher, :type => :models
end

h3. Rails 3

# spec/spec_helper.rb
RSpec.configure do |config|
  config.include AttributeNormalizer::RSpecMatcher, :type => :model
end

p. I will gladly take a patch to add a macro to Test::Unit if someone submits it.

h2. Credits

Original module code and concept was taken from "Dan Kubb":http://github.com/dkubb during a project we worked on together. I found that I was consistently using this across all my projects so I wanted to plugin-er-size and gem this up for easy reuse.

h2. Copyright

Copyright (c) 2009-2010 "Michael Deering(Edmonton Ruby on Rails)":http://mdeering.com See MIT-LICENSE for details.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].