File: README.textile

package info (click to toggle)
ruby-attribute-normalizer 1.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 108 kB
  • sloc: ruby: 213; makefile: 7
file content (191 lines) | stat: -rw-r--r-- 7,542 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
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._

<pre><code># your_initializer.rb
require 'attribute_normalizer'
YourORM::Base.send :include, AttributeNormalizer</code></pre>

h2. Install

<pre><code>sudo gem install attribute_normalizer</code></pre>

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

h3. Rails 2

<pre><code># config/environment.rb
config.gem 'attribute_normalizer'</code></pre>

h3. Rails 3
<pre><code># Gemfile
gem 'attribute_normalizer'</code></pre>

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

<pre><code>./script/plugin install git://github.com/mdeering/attribute_normalizer.git</code></pre>

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.

<pre><code># 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</code></pre>

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.

<pre><code># 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

  # You can enable the attribute normalizers automatically if the specified attributes exist in your column_names. It will use
  # the default normalizers for each attribute (e.g. config.default_normalizers)
  # config.default_attributes = :name, :title

  # Also, You can add a specific attribute to default_attributes using one or more normalizers:
  # config.add_default_attribute :name, :with => :truncate
end
</code></pre>

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

<pre><code>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</code></pre>

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

<pre><code>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'
</code></pre>

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

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

h3. Rails 3

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

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.