cassiomarques-booleanize 0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ 0.2.0 (02 Dec 2008)
2
+ * Now booleanize will receive symbols, arrays or hashes as parameters.
3
+
4
+ 0.1.0 (30 Nov 2008)
5
+ * Initial release
6
+
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2008 [name of plugin creator]
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,135 @@
1
+ = Booleanize
2
+
3
+ Booleanize is a Ruby on Rails plugin that adds new methods to help you work with your models' boolean attributes. Basically, it creates two new instance methods and two named scopes for each specified boolean attribute.
4
+
5
+ == Instance Methods
6
+
7
+ Suppose you have a boolean attribute called <tt>active</tt> inside a User model. If you pass the name of this attribute to the booleanize method, two new methods will be created:
8
+
9
+ * <tt>active?</tt> - Returns if the attribute's value is <tt>true</tt> or <tt>false</tt>
10
+ * <tt>active_humanize</tt> - Returns a string representing each of the <tt>true</tt> or <tt>false</tt> values.
11
+
12
+ === Examples
13
+
14
+ class User < ActiveRecord::Base
15
+ booleanize :active
16
+ end
17
+
18
+ u = User.new(:active => true)
19
+ u.active? #=> true
20
+ u.active_humanize #=> "True"
21
+ u.active = false
22
+ u.active? #=> false
23
+ u.active_humanize #=> "False"
24
+
25
+ You can also specify which strings Booleanize should use for each of the <tt>true</tt> and <tt>false</tt> values, by passing an array with the format [:attr_name, "string for true", "string for false"].
26
+
27
+ class User < ActiveRecord::Base
28
+ booleanize [:active, "Yes", "No"]
29
+ end
30
+
31
+ u = User.new(:active => true)
32
+ u.active_humanize #=> "Yes"
33
+
34
+ == Named scopes
35
+
36
+ Booleanize will create two new named_scopes for each received attribute. Using the example given above, we'll have:
37
+
38
+ * <tt>active</tt> - Will return all the objects for which the <tt>active</tt> boolean attribute is true. It's equivalent to
39
+
40
+ <tt>named_scope :active, :conditions => {:active => true}</tt>
41
+
42
+ * <tt>not_active</tt> - Will return all the objects for which the <tt>active</tt> boolean attribute is false. It's equivalent to
43
+
44
+ <tt>named_scope :not-active, :conditions => {:active => false}</tt>
45
+
46
+ == Booleanizing your booleans
47
+
48
+ The <tt>booleanize</tt> method can receive several parameters. Each parameter can be:
49
+ * A Symbol
50
+ * A Hash like {:attr_name => ['str_for_true', 'str_for_false']}
51
+ * An Array with three elements, like [:attr_name, 'str_for_true', 'str_for_false']
52
+
53
+ class User < ActiveRecord::Base
54
+ booleanize :active, [:smart, "Yes!", "No, very dumb"], :deleted => ["Yes, I'm gone", "No, I'm still here!"]
55
+ end
56
+
57
+ You must pay attention to the fact that the Hash parameter must be the last one (or the only one), otherwise you must enclose it with {...}
58
+
59
+ class User < ActiveRecord::Base
60
+ booleanize {:deleted => ["Yes, I'm gone", "No, I'm still here!"]}, :active, [:smart, "Yes!", "No, very dumb"]
61
+ end
62
+
63
+ But obviously you can pass several key/value pairs in a single Hash
64
+
65
+ class User < ActiveRecord::Base
66
+ booleanize :active => ["Yes, use me!", "No, I'm disabled"], :deleted => ["Yes, I'm gone", "No, I'm still here!"]
67
+ end
68
+
69
+ == Resume
70
+
71
+ It's simple: Instead of writing this:
72
+
73
+ class User < ActiveRecord::Base
74
+ named_scope :active, :conditions => {:active => true}
75
+ named_scope :not_active, :conditions => {:active => false}
76
+
77
+ def active_humanize
78
+ active ? "Yes" : "No"
79
+ end
80
+
81
+ def active?
82
+ active ? true : false #=> because we'll always want it to return true or false, and never nil.
83
+ end
84
+ end
85
+
86
+ You can simply write
87
+
88
+ class User < ActiveRecord::Base
89
+ booleanize :active => ["Yes", "No"]
90
+ end
91
+
92
+ == Installation
93
+
94
+ Just clone the plugin inside <tt>RAILS_ROOT/vendor/plugins</tt>
95
+
96
+ git clone git://github.com/cassiomarques/booleanize.git
97
+
98
+ == Running the tests
99
+
100
+ Booleanize is a fully tested plugin. If you'd like to run the tests, you'll need:
101
+
102
+ * RSpec installed as a gem
103
+ * SQlite3
104
+ * SQlite3 Ruby adapter
105
+
106
+ Just enter the plugin's folder and run
107
+
108
+ rake spec
109
+
110
+ And happilly watch all the tests pass (if everything needed for the tests is installed in your computer).
111
+
112
+ == LICENSE
113
+
114
+ Copyright (c) 2008 Cassio Marques
115
+
116
+ Permission is hereby granted, free of charge, to any person obtaining
117
+ a copy of this software and associated documentation files (the
118
+ "Software"), to deal in the Software without restriction, including
119
+ without limitation the rights to use, copy, modify, merge, publish,
120
+ distribute, sublicense, and/or sell copies of the Software, and to
121
+ permit persons to whom the Software is furnished to do so, subject to
122
+ the following conditions:
123
+
124
+ The above copyright notice and this permission notice shall be
125
+ included in all copies or substantial portions of the Software.
126
+
127
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
128
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
129
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
130
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
131
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
132
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
133
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
134
+
135
+
@@ -0,0 +1,19 @@
1
+ require 'rake'
2
+ require 'spec/rake/spectask'
3
+ require 'rake/rdoctask'
4
+
5
+ desc 'Default: run unit tests.'
6
+ task :default => :spec
7
+
8
+ Spec::Rake::SpecTask.new do |t|
9
+ t.spec_files = FileList['spec/**/*_spec.rb']
10
+ end
11
+
12
+ desc 'Generate documentation for the booleanize plugin.'
13
+ Rake::RDocTask.new(:rdoc) do |rdoc|
14
+ rdoc.rdoc_dir = 'rdoc'
15
+ rdoc.title = 'Booleanize'
16
+ rdoc.options << '--line-numbers' << '--inline-source'
17
+ rdoc.rdoc_files.include('README')
18
+ rdoc.rdoc_files.include('lib/**/*.rb')
19
+ end
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.dirname(__FILE__) + "/lib/booleanize"
@@ -0,0 +1,116 @@
1
+ # = Booleanize plugin
2
+ #
3
+ # This plugin adds some helper methods to boolean attributes in Active Record models.
4
+ # Author: Cassio Marques (cassiommc@gmail.com)
5
+ #
6
+ # = Description
7
+ #
8
+ # Creates two instance methods and two named scopes for each of the received boolean attributes.
9
+ #
10
+ # == Instance methods
11
+ #
12
+ # Creates a attr_name_humanize for each boolean attribute, which returns a specific string for each boolean true or false.
13
+ # Creates a attr_name? method for each boolean attribute.
14
+ #
15
+ # == Named scopes
16
+ #
17
+ # Creates two named scopes for esch boolean attribute:
18
+ # named_scope :attr_name, :conditions => {:attr_name => true}
19
+ # named_scope :not_attr_name, :conditions => {:attr_name => false}
20
+ #
21
+ # == How to use it
22
+ #
23
+ # The <tt>booleanize</tt> method can receive several parameters. Each parameter can be:
24
+ # * A Symbol
25
+ # * A Hash like {:attr_name => ['str_for_true', 'str_for_false']}
26
+ # * A Array with three elements, like [:attr_name, 'str_for_true', 'str_for_false']
27
+ #
28
+ # class User < ActiveRecord::Base
29
+ # booleanize :active, [:smart, "Yes!", "No, very dumb"], :deleted => ["Yes, I'm gone", "No, I'm still here!"]
30
+ # end
31
+ #
32
+ # You must pay attention to the fact that the Hash parameter must be the last one, otherwise you must enclose it with {...}
33
+ #
34
+ # You'll have a humanized instance method for each received boolean attribute:
35
+ #
36
+ # u = User.new(:acive => true. :smart => false)
37
+ # u.smart_humanize #=> "No, very dumb"
38
+ #
39
+ # If you pass a symbol instead of an array, booleanize will use the 'True' default text for boolean true
40
+ # and the 'False' default text for boolean false.
41
+ #
42
+ # booleanize :active, [:smart, "Yes", "No"]
43
+ #
44
+ # u.active_humanize #=> "True"
45
+ # u.active? #=> true
46
+ #
47
+ # You'll also get two new named_scope methods for your model
48
+ #
49
+ # active_users = User.active #=> same as named_scope :active, :conditions => {:active => true}
50
+ # disabled_users = User.not_active #=> same as named_scope :not_active, :conditions => {:active => false}
51
+ #
52
+ module Booleanize
53
+
54
+ def booleanize(*params)
55
+ params.each do |param|
56
+ case param
57
+ when Symbol: create_methods_for_symbol(param)
58
+ when Array: create_methods_for_array(param)
59
+ when Hash: create_methods_for_hash(param)
60
+ else raise_error
61
+ end
62
+ end
63
+ end
64
+
65
+ private
66
+
67
+ def create_true_named_scope(attr_name)
68
+ named_scope attr_name, :conditions => { attr_name => true }
69
+ end
70
+
71
+ def create_false_named_scope(attr_name)
72
+ named_scope :"not_#{attr_name}", :conditions => { attr_name => false }
73
+ end
74
+
75
+ def create_humanize_method(attr_name, true_str, false_str)
76
+ true_str = (true_str.nil? ? "True" : true_str.to_s)
77
+ false_str = (false_str.nil? ? "False" : false_str.to_s)
78
+ class_eval("def #{attr_name}_humanize; #{attr_name} ? #{true_str.inspect} : #{false_str.inspect}; end")
79
+ end
80
+
81
+ def create_methods(attr_name, true_str = nil, false_str = nil)
82
+ create_true_named_scope(attr_name)
83
+ create_false_named_scope(attr_name)
84
+ create_humanize_method(attr_name, true_str, false_str)
85
+ end
86
+
87
+ def create_methods_for_array(array)
88
+ first_is_symbol = array[0].is_a? Symbol
89
+ second_is_string = array[1].is_a? String
90
+ third_is_string = array[2].is_a? String
91
+
92
+ if array.length == 3 && first_is_symbol && second_is_string && third_is_string
93
+ create_methods(array[0], array[1], array[2])
94
+ else
95
+ raise_error(array)
96
+ end
97
+ end
98
+
99
+ def create_methods_for_symbol(symbol)
100
+ create_methods(symbol)
101
+ end
102
+
103
+ def create_methods_for_hash(hash)
104
+ hash.each_pair do |k, v|
105
+ raise_error unless v.is_a? Array and v.length == 2
106
+ create_methods(k, v[0], v[1])
107
+ end
108
+ end
109
+
110
+ def raise_error(param)
111
+ raise "You can only pass a three element Array ([:attr_name, 'str_for_true', 'str_for_false']), a Symbol or a Hash (:attr_name => ['str_for_true', 'str_for_false']). You passed #{param.inspect}"
112
+ end
113
+
114
+ end
115
+
116
+ ActiveRecord::Base.extend Booleanize
@@ -0,0 +1,203 @@
1
+ require 'rubygems'
2
+ require 'spec'
3
+ require 'active_record'
4
+ require File.dirname(__FILE__) + "/../lib/booleanize"
5
+
6
+ ActiveRecord::Base.establish_connection(:adapter=>"sqlite3", :database => ":memory:")
7
+ require File.dirname(__FILE__) + "/db/create_testing_structure"
8
+
9
+ CreateTestingStructure.migrate(:up)
10
+
11
+ class User < ActiveRecord::Base
12
+ booleanize [:dumb, "Dumb as hell!", "No, this is a smart one!"], :active, [:smart, "Yes!", "No, very dumb"], :deleted => ["Yes, I'm gone", "No, I'm still here!"]
13
+ end
14
+
15
+ class Post < ActiveRecord::Base
16
+ booleanize :deleted => ["Yes", "No"], :rated => ["Yes", "No"]
17
+ end
18
+
19
+ describe "booleanize" do
20
+ def smart_user
21
+ User.new(:name => "Smart Dude", :active => true, :dumb => false, :smart => true, :deleted => false)
22
+ end
23
+
24
+ def dumb_user
25
+ User.new(:name => "Dumb Dude", :active => true, :dumb => true, :smart => false, :deleted => false)
26
+ end
27
+
28
+ it "should raise an exception if any of the attributes is not a Symbol or a three elements array" do
29
+ lambda do
30
+ class Bla < ActiveRecord::Base
31
+ booleanize "bla"
32
+ end
33
+ end.should raise_error
34
+ end
35
+
36
+ it "should raise an exception if it receives an array but it's not in the format [:attr_name, 'string for true', 'string for false']" do
37
+ lambda do
38
+ class Bla < ActiveRecord::Base
39
+ booleanize [:bla]
40
+ end.should raise_error
41
+ end
42
+ lambda do
43
+ class Bla < ActiveRecord::Base
44
+ booleanize [:bla, 'Yes!']
45
+ end
46
+ end.should raise_error
47
+ lambda do
48
+ class Bla < ActiveRecord::Base
49
+ booleanize [:bla, 'Yes!', :no]
50
+ end
51
+ end.should raise_error
52
+ end
53
+
54
+ it "should raise an exception if it receives a hash but it's not in the format :attr_name => ['str_for_true', 'str_for_false']" do
55
+ lambda do
56
+ class Bla < ActiveRecord::Base
57
+ booleanize :attr_nam => []
58
+ end.should raise_error
59
+ end
60
+ lambda do
61
+ class Bla < ActiveRecord::Base
62
+ booleanize :attr_name => ['str_for_true']
63
+ end
64
+ end.should raise_error
65
+ lambda do
66
+ class Bla < ActiveRecord::Base
67
+ booleanize :attr_name => ['bla', 'ble', 'bli']
68
+ end.should raise_error
69
+ end
70
+ end
71
+
72
+ describe "creating boolean_attr_name? method" do
73
+ it "should respond to a boolean_attr_name? for each received attribute" do
74
+ u = smart_user
75
+ [:active?, :dumb?, :smart?].each {|m| u.should respond_to(m)}
76
+ end
77
+
78
+ it "should return true if the attribute's value is true'" do
79
+ smart_user.should be_smart
80
+ smart_user.should_not be_dumb
81
+ end
82
+
83
+ it "should return false if the attribute's value is false" do
84
+ dumb_user.should be_dumb
85
+ dumb_user.should_not be_smart
86
+ end
87
+
88
+ it "should return the new boolean value when a new value is assigned to the attribute" do
89
+ u = smart_user
90
+ u.active = false
91
+ u.should_not be_active
92
+ end
93
+
94
+ it "should return false is the attribute is nil" do
95
+ u = smart_user
96
+ u.active = nil
97
+ u.active?.should == false
98
+ end
99
+ end
100
+
101
+ describe "creating boolean_attr_name_humanize method" do
102
+ describe "when a symbol is passed" do
103
+ it "should respond to a boolean_attr_name_humanize method for each received attribute" do
104
+ u = dumb_user
105
+ [:active_humanize, :dumb_humanize, :smart_humanize].each {|m| u.should respond_to(m)}
106
+ end
107
+ end
108
+
109
+ describe "when an array is passed" do
110
+ it "should return the specified string for true" do
111
+ smart_user.smart_humanize.should eql("Yes!")
112
+ end
113
+
114
+ it "should return the specified string for false" do
115
+ dumb_user.smart_humanize.should eql("No, very dumb")
116
+ end
117
+
118
+ it "should return the string for false when the attribute is nil" do
119
+ u = dumb_user
120
+ u.smart = nil
121
+ u.smart_humanize.should == "No, very dumb"
122
+ end
123
+ end
124
+
125
+ describe "when a hash is passed" do
126
+ it "should return the specified string for true" do
127
+ u = smart_user
128
+ u.deleted = true
129
+ u.deleted_humanize.should eql("Yes, I'm gone")
130
+ end
131
+
132
+ it "should return the specified string for false" do
133
+ smart_user.deleted_humanize.should eql("No, I'm still here!")
134
+ end
135
+
136
+ it "should return the string for false when the attribute is nil" do
137
+ u = smart_user
138
+ u.deleted = nil
139
+ u.deleted_humanize.should eql("No, I'm still here!")
140
+ end
141
+
142
+ it "should respond to attr_name?" do
143
+ smart_user.should respond_to(:deleted)
144
+ end
145
+
146
+ describe "with more than on key/value pair" do
147
+ it "should create a 'humanize' method for each key" do
148
+ p = Post.new(:rated => true, :deleted => false)
149
+ p.rated_humanize.should eql("Yes")
150
+ p.deleted_humanize.should eql("No")
151
+ end
152
+ end
153
+ end
154
+
155
+ describe "when a symbol is passed" do
156
+ it "should return the default string for true" do
157
+ smart_user.active_humanize.should eql("True")
158
+ end
159
+
160
+ it "should return the default string for false" do
161
+ u = smart_user
162
+ u.active = false
163
+ u.active_humanize.should eql("False")
164
+ end
165
+
166
+ it "should return the string for false when the attribute is nil" do
167
+ u = smart_user
168
+ u.active = false
169
+ u.active_humanize.should eql("False")
170
+ end
171
+ end
172
+ end
173
+
174
+ describe "creating named_scopes" do
175
+ before do
176
+ 3.times {|i| smart_user.save!; dumb_user.save! }
177
+ end
178
+
179
+ after do
180
+ User.delete_all
181
+ end
182
+
183
+ it "should have a named scope that returns all the objects for which the boolean attribute is true" do
184
+ User.smart.should have(3).items
185
+ User.active.should have(6).items
186
+ end
187
+
188
+ it "should have a named scope that returns all the objects for which the boolean attribute is false" do
189
+ User.not_smart.should have(3).items
190
+ User.not_active.should be_empty
191
+ end
192
+
193
+ it "should have a named scope that returns all the objects for which a boolean attribute passed as a hash is true" do
194
+ User.deleted.should be_empty
195
+ end
196
+
197
+ it "should have a named scope that returns all the objects for which a boolean attribute passed as a hash is false" do
198
+ User.not_deleted.should have(6).items
199
+ end
200
+ end
201
+ end
202
+
203
+
@@ -0,0 +1,20 @@
1
+ class CreateTestingStructure < ActiveRecord::Migration
2
+ def self.up
3
+ create_table :users do |t|
4
+ t.string :name
5
+ t.boolean :smart
6
+ t.boolean :active
7
+ t.boolean :dumb
8
+ t.boolean :deleted
9
+ end
10
+ create_table :posts do |t|
11
+ t.boolean :deleted
12
+ t.boolean :rated
13
+ end
14
+ end
15
+
16
+ def self.down
17
+ drop_table :users
18
+ drop_table :posts
19
+ end
20
+ end
metadata ADDED
@@ -0,0 +1,60 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: cassiomarques-booleanize
3
+ version: !ruby/object:Gem::Version
4
+ version: "0.1"
5
+ platform: ruby
6
+ authors:
7
+ - "C\xC3\xA1ssio Marques"
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2009-05-04 00:00:00 -07:00
13
+ default_executable:
14
+ dependencies: []
15
+
16
+ description: A Rails plugin that adds some new methods for boolean attributes in Active Record models.
17
+ email: cassiommc@gmail.com
18
+ executables: []
19
+
20
+ extensions: []
21
+
22
+ extra_rdoc_files:
23
+ - README.rdoc
24
+ files:
25
+ - CHANGELOG
26
+ - MIT-LICENSE
27
+ - README.rdoc
28
+ - Rakefile
29
+ - init.rb
30
+ - lib/booleanize.rb
31
+ has_rdoc: true
32
+ homepage: http://github.com/cassiomarques/booleanize
33
+ post_install_message:
34
+ rdoc_options:
35
+ - --main
36
+ - README.rdoc
37
+ require_paths:
38
+ - lib
39
+ required_ruby_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: "0"
44
+ version:
45
+ required_rubygems_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: "0"
50
+ version:
51
+ requirements: []
52
+
53
+ rubyforge_project:
54
+ rubygems_version: 1.2.0
55
+ signing_key:
56
+ specification_version: 2
57
+ summary: A Rails plugin that adds some new methods for boolean attributes in Active Record models.
58
+ test_files:
59
+ - spec/booleanize_spec.rb
60
+ - spec/db/create_testing_structure.rb