linki-symbolize 1.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
@@ -0,0 +1,5 @@
1
+ .DS_Store
2
+ coverage
3
+ rdoc
4
+ doc
5
+ pkg
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2007-2008 Andreas Neuhaus <zargony@zargony.com>
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,187 @@
1
+ = Symbolize attribute values in ActiveRecord (e.g. for nicer enums)
2
+
3
+ This plugin introduces an easy way to use symbols for values of ActiveRecord
4
+ attributes. Symbolized attributes return a ruby symbol (or nil) as their value
5
+ and can be set using symbols.
6
+
7
+
8
+ == About
9
+
10
+ Since ActiveRecord does not natively support database column types of ENUM or
11
+ SET, you'll usually use a string attribute and restrict it to certain values
12
+ with validations. Using this plugin, the values of such pseudo-enums are
13
+ symbols, which look more ruby-style than strings.
14
+
15
+ Simply add "symbolize :attr_name" to your model class, and the specified
16
+ attribute will return symbol values and can be set using smbols (setting
17
+ string values will still work, which is important when using forms).
18
+
19
+ An attribute to symbolize should be a string (varchar) column in the database.
20
+
21
+ Blog: http://zargony.com/
22
+ Github: http://github.com/zargony/activerecord_symbolize
23
+
24
+
25
+ == Install
26
+
27
+ Gem:
28
+
29
+ gem install gemcutter
30
+ gem tumble
31
+ gem install symbolize
32
+ config.gem "symbolize", :source => 'http://gemcutter.org'
33
+
34
+
35
+ Plugin:
36
+
37
+ ./script/plugin install git://github.com/nofxx/activerecord_symbolize.git
38
+
39
+
40
+ == Usage
41
+
42
+ Add "symbolize :attr_name" to your model class. You may also want to add
43
+ validates_inclusion_of to restrict the possible values (just like an enum).
44
+
45
+ class User < ActiveRecord::Base
46
+ symbolize :gender, :in => [:female, :male], :scopes => true
47
+ symbolize :so, :in => {
48
+ :linux => "Linux",
49
+ :mac => "Mac OS X"
50
+ }, :scopes => true
51
+ symbolize :gui, , :in => [:gnome, :kde, :xfce], :allow_blank => true
52
+ symbolize :browser, :in => [:firefox, :opera], :i18n => false, :methods => true
53
+ symbolize :angry, :in => [true, false], :scopes => true
54
+ end
55
+
56
+ === in/within
57
+
58
+ The values allowed on the enum field, you can provide a hash with
59
+ {:value => "Human text"} or an array of keys to be i18n eval (or not).
60
+ Booleans are also supported. See below.
61
+
62
+ allow_(blank|nil): What you expect.
63
+
64
+
65
+ === i18n
66
+
67
+ If you don`t provide a hash with values, it will try i18n:
68
+
69
+ activerecord:
70
+ attributes:
71
+ user:
72
+ enums:
73
+ gui:
74
+ gnome: Gnome Desktop Enviroment
75
+ kde: K Desktop Enviroment
76
+ xfce: XFCE4
77
+ gender:
78
+ female: Girl
79
+ male: Boy
80
+
81
+ You can skip i18n lookup with :i18n => false
82
+ symbolize :gender, :in => [:female, :male], :i18n => false
83
+
84
+
85
+ === method
86
+
87
+ If you provide the method option, some fancy boolean methods will be added:
88
+ In our User example, browser has this option, so you can do:
89
+
90
+ @user.firefox?
91
+ @user.opera?
92
+
93
+
94
+ === Booleans
95
+
96
+ Its possible to use boolean fields also.
97
+ symbolize :switch, :in => [true, false]
98
+
99
+ ...
100
+ switch:
101
+ "true": On
102
+ "false": Off
103
+ "nil": Unknown
104
+
105
+
106
+ === scopes (BETA)
107
+
108
+ If you provide the scopes option, some fancy named scopes will be added:
109
+ In our User example, gender has this option, so you can do:
110
+
111
+ User.female => User.find(:all, :conditions => { :gender => :female })
112
+
113
+ You can chain named scopes as well:
114
+
115
+ User.female.mac => User.find(:all, :conditions => { :gender => :female, :so => :mac })
116
+
117
+ For boolean colums you can use
118
+
119
+ User.angry => User.find(:all, :conditions => { :angry => true })
120
+ User.not_angry => User.find(:all, :conditions => { :angry => false })
121
+
122
+ ( or with_[attribute] and without_[attribute] )
123
+
124
+
125
+ == Examples
126
+
127
+ u = User.find_by_name('Anna') # => #<User Anna>
128
+ u.gender # => :female
129
+
130
+ u = User.find_by_gender(:male) # => #<User Bob>
131
+ u.gender # => :male
132
+
133
+ u = User.find(:all, :conditions => { :gender => :female })
134
+ u = User.female
135
+
136
+ u = User.new(:name => 'ET', :gender => :unknown)
137
+ u.save # => validation fails
138
+
139
+
140
+ == Examples Helpers
141
+
142
+ <% form_for @user do |f| %>
143
+ <%= f.radio_sym "gender" %>
144
+ <!-- Alphabetic order -->
145
+ <%= f.select_sym "so" %>
146
+ <!-- Fixed order -->
147
+ <%= f.select_sym "office" %>
148
+ <% end %>
149
+
150
+ output:
151
+
152
+ <form action="users/1" method="post">
153
+ <div style="margin:0;padding:0">...</div>
154
+ <label>Female <input id="user_gender_female" name="user[gender]" type="radio" value="female"></label>
155
+ <label>Male <input checked="checked" id="user_gender_male" name="user[gender]" type="radio" value="male" ></label>
156
+ <!-- Alphabetic order -->
157
+ <select id="user_so" name="post[so]">
158
+ <option value="linux" selected="selected">Linux</option>
159
+ <option value="mac">Mac OS X</option>
160
+ <option value="windows">Windows XP</option>
161
+ </select>
162
+ <!-- Fixed order -->
163
+ <select id="user_office" name="post[office]">
164
+ <option value="kde" selected="selected">Koffice</option>
165
+ <option value="ms">Microsoft Office</option>
166
+ <option value="open">Open Office</option>
167
+ </select>
168
+ </form>
169
+
170
+
171
+ == Notes
172
+
173
+ This fork:
174
+ http://github.com/nofxx/symbolize
175
+
176
+
177
+ Forked from:
178
+ http://github.com/nuxlli/activerecord_symbolize
179
+
180
+
181
+ Initial work:
182
+ I've been using this for quite some time and made it a rails plugin now. More
183
+ background iinformation can be found at
184
+ http://zargony.com/2007/09/07/symbolize-attribute-values-in-activerecord
185
+
186
+
187
+ Copyright (c) 2007-2008 Andreas Neuhaus, released under the MIT license
@@ -0,0 +1,54 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'spec/rake/spectask'
4
+
5
+ begin
6
+ require 'jeweler'
7
+ Jeweler::Tasks.new do |gem|
8
+ gem.name = "linki-symbolize"
9
+ gem.summary = "ActiveRecord enums with i18n"
10
+ gem.description = "ActiveRecord enums with i18n"
11
+ gem.email = "m.linkhorst@googlemail.com"
12
+ gem.homepage = "http://github.com/linki/symbolize"
13
+ gem.authors = ["Marcos Piccinini", "Martin Linkhorst"]
14
+ gem.add_development_dependency "rspec"
15
+ end
16
+ Jeweler::GemcutterTasks.new
17
+ rescue LoadError
18
+ puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler"
19
+ end
20
+
21
+ Spec::Rake::SpecTask.new(:spec) do |spec|
22
+ spec.libs << 'lib' << 'spec'
23
+ spec.spec_files = FileList['spec/**/*_spec.rb']
24
+ end
25
+
26
+ Spec::Rake::SpecTask.new(:rcov) do |spec|
27
+ spec.libs << 'lib' << 'spec'
28
+ spec.pattern = 'spec/**/*_spec.rb'
29
+ spec.rcov = true
30
+ end
31
+ task :default => :spec
32
+
33
+ # desc 'Generate documentation for the activerecord_symbolize plugin.'
34
+ # Rake::RDocTask.new(:rdoc) do |rdoc|
35
+ # rdoc.rdoc_dir = 'rdoc'
36
+ # rdoc.title = 'ActiverecordSymbolize'
37
+ # rdoc.options << '--line-numbers' << '--inline-source'
38
+ # rdoc.rdoc_files.include('README')
39
+ # rdoc.rdoc_files.include('lib/**/*.rb')
40
+ # end
41
+ require 'rake/rdoctask'
42
+ Rake::RDocTask.new do |rdoc|
43
+ if File.exist?('VERSION.yml')
44
+ config = YAML.load(File.read('VERSION.yml'))
45
+ version = "#{config[:major]}.#{config[:minor]}.#{config[:patch]}"
46
+ else
47
+ version = ""
48
+ end
49
+
50
+ rdoc.rdoc_dir = 'rdoc'
51
+ rdoc.title = "symbolize #{version}"
52
+ rdoc.rdoc_files.include('README*')
53
+ rdoc.rdoc_files.include('lib/**/*.rb')
54
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.1.0
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.dirname(__FILE__) + "/rails/init"
@@ -0,0 +1,176 @@
1
+ module Symbolize
2
+ def self.included base
3
+ base.extend(ClassMethods)
4
+ end
5
+
6
+ # Symbolize ActiveRecord attributes. Add
7
+ # symbolize :attr_name
8
+ # to your model class, to make an attribute return symbols instead of
9
+ # string values. Setting such an attribute will accept symbols as well
10
+ # as strings. In the database, the symbolized attribute should have
11
+ # the column-type :string.
12
+ #
13
+ # Example:
14
+ # class User < ActiveRecord::Base
15
+ # symbolize :gender, :in => [:female, :male]
16
+ # symbolize :so, :in => {
17
+ # :linux => "Linux",
18
+ # :mac => "Mac OS X"
19
+ # }
20
+ # symbolize :gui, , :in => [:gnome, :kde, :xfce], :allow_blank => true
21
+ # symbolize :browser, :in => [:firefox, :opera], :i18n => false
22
+ # end
23
+ #
24
+ # It will automattically lookup for i18n:
25
+ #
26
+ # activerecord:
27
+ # attributes:
28
+ # user:
29
+ # enums:
30
+ # gender:
31
+ # female: Girl
32
+ # male: Boy
33
+ #
34
+ # You can skip i18n lookup with :i18n => false
35
+ # symbolize :gender, :in => [:female, :male], :i18n => false
36
+ #
37
+ # Its possible to use boolean fields also.
38
+ # symbolize :switch, :in => [true, false]
39
+ #
40
+ # ...
41
+ # switch:
42
+ # "true": On
43
+ # "false": Off
44
+ # "nil": Unknown
45
+ #
46
+ module ClassMethods
47
+ # Specifies that values of the given attributes should be returned
48
+ # as symbols. The table column should be created of type string.
49
+ def symbolize *attr_names
50
+ configuration = {}
51
+ configuration.update(attr_names.extract_options!)
52
+
53
+ enum = configuration[:in] || configuration[:within]
54
+ i18n = configuration[:i18n].nil? && !enum.instance_of?(Hash) && enum ? true : configuration[:i18n]
55
+ methods = configuration[:methods]
56
+ scopes = configuration[:scopes]
57
+ validation = configuration[:validation] != false
58
+
59
+ unless enum.nil?
60
+ # Little monkeypatching, <1.8 Hashes aren't ordered.
61
+ hsh = if RUBY_VERSION > '1.9' || !defined?('ActiveSupport')
62
+ Hash
63
+ else
64
+ ActiveSupport::OrderedHash
65
+ end
66
+
67
+ attr_names.each do |attr_name|
68
+ attr_name = attr_name.to_s
69
+ if enum.instance_of?(Hash)
70
+ values = enum
71
+ else
72
+ if i18n
73
+ values = hsh[*enum.map { |v| [v, I18n.translate("activerecord.attributes.#{ActiveSupport::Inflector.underscore(self)}.enums.#{attr_name}.#{v}")] }.flatten]
74
+ else
75
+ values = hsh[*enum.map { |v| [v, (configuration[:capitalize] ? v.to_s.capitalize : v.to_s)] }.flatten]
76
+ end
77
+ end
78
+
79
+ # Get the values of :in
80
+ const = "#{attr_name}_values"
81
+ const_set const.upcase, values unless const_defined? const.upcase
82
+ # This one is a dropdown helper
83
+ class_eval "def self.get_#{const}; #{const.upcase}.map(&:reverse); end"
84
+
85
+ if methods
86
+ values.each do |value|
87
+ define_method("#{value[0]}?") do
88
+ self.send(attr_name) == value[0]
89
+ end
90
+ end
91
+ end
92
+
93
+ if scopes
94
+ values.each do |value|
95
+ if value[0].respond_to?(:to_sym)
96
+ named_scope value[0].to_sym, :conditions => { attr_name => value[0].to_sym }
97
+ else
98
+ if value[0] == true || value[0] == false
99
+ named_scope "with_#{attr_name}", :conditions => { attr_name => true }
100
+ named_scope "without_#{attr_name}", :conditions => { attr_name => false }
101
+
102
+ named_scope attr_name, :conditions => { attr_name => true }
103
+ named_scope "not_#{attr_name}", :conditions => { attr_name => false }
104
+ end
105
+ end
106
+ end
107
+ end
108
+ end
109
+
110
+ if validation
111
+ class_eval "validates_inclusion_of :#{attr_names.join(', :')}, configuration"
112
+ end
113
+ end
114
+
115
+ attr_names.each do |attr_name|
116
+ attr_name = attr_name.to_s
117
+ class_eval("def #{attr_name}; read_and_symbolize_attribute('#{attr_name}'); end")
118
+ class_eval("def #{attr_name}= (value); write_symbolized_attribute('#{attr_name}', value); end")
119
+ if i18n
120
+ class_eval("def #{attr_name}_text; read_i18n_attribute('#{attr_name}'); end")
121
+ elsif enum
122
+ class_eval("def #{attr_name}_text; #{attr_name.upcase}_VALUES[#{attr_name}]; end")
123
+ else
124
+ class_eval("def #{attr_name}_text; #{attr_name}.to_s; end")
125
+ end
126
+ end
127
+ end
128
+ end
129
+
130
+ # String becomes symbol, booleans string and nil nil.
131
+ def symbolize_attribute attr
132
+ case attr
133
+ when String then attr.empty? ? nil : attr.to_sym
134
+ when Symbol, TrueClass, FalseClass then attr
135
+ else nil
136
+ end
137
+ end
138
+
139
+ # Return an attribute's value as a symbol or nil
140
+ def read_and_symbolize_attribute attr_name
141
+ symbolize_attribute read_attribute(attr_name)
142
+ end
143
+
144
+ # Return an attribute's i18n
145
+ def read_i18n_attribute attr_name
146
+ I18n.translate("activerecord.attributes.#{ActiveSupport::Inflector.underscore(self.class)}.enums.#{attr_name}.#{read_attribute(attr_name)}") #.to_sym rescue nila
147
+ end
148
+
149
+ # Write a symbolized value. Watch out for booleans.
150
+ def write_symbolized_attribute attr_name, value
151
+ val = { "true" => true, "false" => false }[value]
152
+ val = symbolize_attribute(value) if val.nil?
153
+ write_attribute(attr_name, val)
154
+ end
155
+ end
156
+
157
+ # The Symbol class is extended by method quoted_id which returns a string.
158
+ # The idea behind this is, that symbols are converted to plain strings
159
+ # when being quoted by ActiveRecord::ConnectionAdapters::Quoting#quote.
160
+ # This makes it possible to work with symbolized attibutes in sql conditions.
161
+ # E.g. validates_uniqueness_of could not use :scope with a symbolized
162
+ # attribute, because AR quotes it to YAML:
163
+ # "... AND status = '--- :active\n'"
164
+ # Having support for quoted_id in Symbol, makes AR quoting symbols correctly:
165
+ # "... AND status = 'active'"
166
+ # NOTE: Normally quoted_id should be implemented as a singleton method
167
+ # only used on symbols returned by read_and_symbolize_attribute,
168
+ # but unfortunately this is not possible since Symbol is an immediate
169
+ # value and therefore does not support singleton methods.
170
+ class Symbol
171
+ def quoted_id
172
+ # A symbol can contain almost every character (even a backslash or an
173
+ # apostrophe), so make sure to properly quote the string value here.
174
+ "'#{ActiveRecord::Base.connection.quote_string(self.to_s)}'"
175
+ end
176
+ end
@@ -0,0 +1,60 @@
1
+ # Goes in lib/meta_tag_helper.rb
2
+ module ActionView
3
+ module Helpers
4
+ module FormHelper
5
+ # helper to create a select drop down list for the symbolize values
6
+ def select_sym(object, method, choices = nil, options = {}, html_options = {})
7
+
8
+ InstanceTag.new(object, method, self, options.delete(:object)).
9
+ to_select_sym_tag(choices, options, html_options)
10
+ end
11
+
12
+ def radio_sym(object, method, choices = nil, options = {})
13
+ InstanceTag.new(object, method, self, options.delete(:object)).
14
+ to_radio_sym_tag(choices, options)
15
+ end
16
+ end
17
+
18
+ class FormBuilder
19
+ def select_sym(method, choices = nil, options = {}, html_options = {})
20
+ @template.select_sym(@object_name, method, choices, options, html_options)
21
+ end
22
+
23
+ def radio_sym(method, choices = nil, options = {})
24
+ @template.radio_sym(@object_name, method, choices, options)
25
+ end
26
+ end
27
+
28
+ class InstanceTag
29
+ # Create a select tag and one option for each of the
30
+ # symbolize values.
31
+ def to_select_sym_tag(choices, options, html_options)
32
+ choices = symbolize_values(choices)
33
+ to_select_tag(choices, options, html_options)
34
+ end
35
+
36
+ def to_radio_sym_tag(choices, options)
37
+ choices = symbolize_values(choices)
38
+ raise ArgumentError, "No values for radio tag" unless choices
39
+ add_default_name_and_id(options)
40
+ v = value(object)
41
+ tag_text = ''
42
+ template = options.dup
43
+ template.delete('checked')
44
+ choices.each do |choice|
45
+ opts = template.dup
46
+ opts['checked'] = 'checked' if v and v == choice[1]
47
+ opts['id'] = "#{opts['id']}_#{choice[1]}"
48
+ tag_text << "<label>#{choice[0]}: "
49
+ tag_text << to_radio_button_tag(choice[1], opts)
50
+ tag_text << "</label>"
51
+ end
52
+ tag_text
53
+ end
54
+
55
+ def symbolize_values(choices)
56
+ choices.nil? ? object.class.send("get_#{@method_name}_values") : choices
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,60 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = %q{linki-symbolize}
8
+ s.version = "1.1.0"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Marcos Piccinini", "Martin Linkhorst"]
12
+ s.date = %q{2009-12-02}
13
+ s.description = %q{ActiveRecord enums with i18n}
14
+ s.email = %q{m.linkhorst@googlemail.com}
15
+ s.extra_rdoc_files = [
16
+ "README.rdoc"
17
+ ]
18
+ s.files = [
19
+ ".document",
20
+ ".gitignore",
21
+ "MIT-LICENSE",
22
+ "README.rdoc",
23
+ "Rakefile",
24
+ "VERSION",
25
+ "init.rb",
26
+ "lib/symbolize.rb",
27
+ "lib/symbolize_helper.rb",
28
+ "linki-symbolize.gemspec",
29
+ "rails/init.rb",
30
+ "spec/db/create_testing_structure.rb",
31
+ "spec/locales/pt.yml",
32
+ "spec/spec_helper.rb",
33
+ "spec/symbolize_spec.rb",
34
+ "symbolize.gemspec"
35
+ ]
36
+ s.homepage = %q{http://github.com/linki/symbolize}
37
+ s.rdoc_options = ["--charset=UTF-8"]
38
+ s.require_paths = ["lib"]
39
+ s.rubygems_version = %q{1.3.5}
40
+ s.summary = %q{ActiveRecord enums with i18n}
41
+ s.test_files = [
42
+ "spec/db/create_testing_structure.rb",
43
+ "spec/spec_helper.rb",
44
+ "spec/symbolize_spec.rb"
45
+ ]
46
+
47
+ if s.respond_to? :specification_version then
48
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
49
+ s.specification_version = 3
50
+
51
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
52
+ s.add_development_dependency(%q<rspec>, [">= 0"])
53
+ else
54
+ s.add_dependency(%q<rspec>, [">= 0"])
55
+ end
56
+ else
57
+ s.add_dependency(%q<rspec>, [">= 0"])
58
+ end
59
+ end
60
+
@@ -0,0 +1,2 @@
1
+ require File.join(File.dirname(__FILE__), '..', "lib", "symbolize_helper")
2
+ ActiveRecord::Base.send(:include, Symbolize)
@@ -0,0 +1,18 @@
1
+ class CreateTestingStructure < ActiveRecord::Migration
2
+ def self.up
3
+ create_table :users do |t|
4
+ t.string :name, :so, :gui, :other, :status, :language
5
+ t.string :limited, :limit => 10
6
+ t.string :karma, :limit => 5
7
+ t.boolean :sex
8
+ t.boolean :public
9
+ end
10
+ create_table :user_skills do |t|
11
+ t.string :kind
12
+ end
13
+ end
14
+
15
+ def self.down
16
+ drop_table :users
17
+ end
18
+ end
@@ -0,0 +1,16 @@
1
+ pt:
2
+ activerecord:
3
+ attributes:
4
+ user:
5
+ enums:
6
+ language:
7
+ pt: Português
8
+ en: Inglês
9
+ sex:
10
+ "true": Feminino
11
+ "false": Masculino
12
+ user_skill:
13
+ enums:
14
+ kind:
15
+ magic: Mágica
16
+ agility: Agilidade
@@ -0,0 +1,22 @@
1
+ require 'rubygems'
2
+ require 'spec'
3
+
4
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
5
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
6
+ require 'active_record'
7
+ require 'action_controller'
8
+ require 'action_view'
9
+ require 'symbolize'
10
+ require File.join(File.dirname(__FILE__), '..', 'init')
11
+
12
+ ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
13
+ require File.dirname(__FILE__) + "/db/create_testing_structure"
14
+ I18n.load_path += Dir[File.join(File.dirname(__FILE__), "locales", "*.{rb,yml}")]
15
+ I18n.default_locale = "pt"
16
+ CreateTestingStructure.migrate(:up)
17
+
18
+
19
+ Spec::Runner.configure do |config|
20
+
21
+
22
+ end
@@ -0,0 +1,266 @@
1
+ # -*- coding: utf-8 -*-
2
+ require File.dirname(__FILE__) + '/spec_helper'
3
+
4
+ #
5
+ # Test model
6
+ class User < ActiveRecord::Base
7
+ symbolize :other
8
+ symbolize :language, :in => [:pt, :en]
9
+ symbolize :sex, :in => [true, false], :scopes => true
10
+ symbolize :status , :in => [:active, :inactive], :i18n => false, :capitalize => true, :scopes => true
11
+ symbolize :so, :allow_blank => true, :in => {
12
+ :linux => 'Linux',
13
+ :mac => 'Mac OS X',
14
+ :win => 'Videogame'
15
+ }, :scopes => true
16
+ symbolize :gui, :allow_blank => true, :in => [:cocoa, :qt, :gtk], :i18n => false
17
+ symbolize :karma, :in => [:good, :bad, :ugly], :methods => true, :i18n => false, :allow_nil => true
18
+ symbolize :public, :in => [true, false], :scopes => true
19
+ end
20
+
21
+ class UserSkill < ActiveRecord::Base
22
+ symbolize :kind, :in => [:agility, :magic]
23
+ end
24
+
25
+ # Make with_scope public-usable for testing
26
+ class << ActiveRecord::Base
27
+ public :with_scope
28
+ end
29
+
30
+ # Test records
31
+ User.create(:name => 'Anna', :other => :fo, :status => :active , :so => :linux, :gui => :qt, :language => :pt, :sex => true, :public => true)
32
+ User.create(:name => 'Bob' , :other => :bar,:status => :inactive, :so => :mac, :gui => :gtk, :language => :en, :sex => false, :public => false)
33
+
34
+
35
+ describe "Symbolize" do
36
+
37
+
38
+ it "should respond to symbolize" do
39
+ ActiveRecord::Base.should respond_to :symbolize
40
+ end
41
+
42
+ describe "Instantiated" do
43
+ before(:each) do
44
+ @user = User.first
45
+ end
46
+
47
+ it "test_symbolize_string" do
48
+ @user.status = 'inactive'
49
+ @user.status.should eql(:inactive)
50
+ # @user.status_before_type_cast.should eql(:inactive)
51
+ # @user.read_attribute(:status).should eql('inactive')
52
+ end
53
+
54
+ it "test_symbolize_symbol" do
55
+ @user.status = :active
56
+ @user.status.should eql(:active)
57
+ @user.status_before_type_cast.should eql(:active)
58
+ # @user.read_attribute(:status).should eql('active')
59
+ end
60
+
61
+ it "should acts nice with numbers" do
62
+ @user.status = 43
63
+ @user.status.should be_nil
64
+ @user.status_before_type_cast.should be_nil
65
+ @user.read_attribute(:status).should be_nil
66
+ end
67
+
68
+ it "should acts nice with nil" do
69
+ @user.status = nil
70
+ @user.status.should be_nil
71
+ @user.status_before_type_cast.should be_nil
72
+ @user.read_attribute(:status).should be_nil
73
+ end
74
+
75
+ it "should acts nice with blank" do
76
+ @user.status = ""
77
+ @user.status.should be_nil
78
+ @user.status_before_type_cast.should be_nil
79
+ @user.read_attribute(:status).should be_nil
80
+ end
81
+
82
+ it "test_symbols_quoted_id" do
83
+ @user.status = :active
84
+ @user.status.quoted_id.should eql("'active'")
85
+ end
86
+
87
+ it "should not validates other" do
88
+ @user.other = nil
89
+ @user.should be_valid
90
+ @user.other = ""
91
+ @user.should be_valid
92
+ end
93
+
94
+ it "should get the correct values" do
95
+ User.get_status_values.should eql([["Active", :active],["Inactive", :inactive]])
96
+ User::STATUS_VALUES.should eql({:inactive=>"Inactive", :active=>"Active"})
97
+ end
98
+
99
+ it "test_symbolize_humanize" do
100
+ @user.status_text.should eql("Active")
101
+ end
102
+
103
+ it "should get the correct values" do
104
+ User.get_gui_values.should =~ [["cocoa", :cocoa], ["qt", :qt], ["gtk", :gtk]]
105
+ User::GUI_VALUES.should eql({:cocoa=>"cocoa", :qt=>"qt", :gtk=>"gtk"})
106
+ end
107
+
108
+ it "test_symbolize_humanize" do
109
+ @user.gui_text.should eql("qt")
110
+ end
111
+
112
+ it "should get the correct values" do
113
+ User.get_so_values.should =~ [["Linux", :linux], ["Mac OS X", :mac], ["Videogame", :win]]
114
+ User::SO_VALUES.should eql({:linux => "Linux", :mac => "Mac OS X", :win => "Videogame"})
115
+ end
116
+
117
+ it "test_symbolize_humanize" do
118
+ @user.so_text.should eql("Linux")
119
+ end
120
+
121
+ it "test_symbolize_humanize" do
122
+ @user.so = :mac
123
+ @user.so_text.should eql("Mac OS X")
124
+ end
125
+
126
+ it "should stringify" do
127
+ @user.other_text.should eql("fo")
128
+ @user.other = :foo
129
+ @user.other_text.should eql("foo")
130
+ end
131
+
132
+ it "should validate status" do
133
+ @user.status = nil
134
+ @user.should_not be_valid
135
+ @user.should have(1).errors
136
+ end
137
+
138
+ it "should not validate so" do
139
+ @user.so = nil
140
+ @user.should be_valid
141
+ end
142
+
143
+ it "test_symbols_with_weird_chars_quoted_id" do
144
+ @user.status = :"weird'; chars"
145
+ @user.status_before_type_cast.should eql(:"weird'; chars")
146
+ # assert_equal "weird'; chars", @user.read_attribute(:status)
147
+ # assert_equal "'weird''; chars'", @user.status.quoted_id
148
+ end
149
+
150
+ it "test_symbolized_finder" do
151
+ User.find(:all, :conditions => { :status => :inactive }).map(&:name).should eql(['Bob'])
152
+ User.find_all_by_status(:inactive).map(&:name).should eql(['Bob'])
153
+ end
154
+
155
+ it "test_symbolized_with_scope" do
156
+ User.with_scope(:find => { :conditions => { :status => :inactive }}) do
157
+ User.find(:all).map(&:name).should eql(['Bob'])
158
+ end
159
+ end
160
+
161
+ it "should have named scopes" do
162
+ anna = User.find_by_name!('Anna')
163
+ bob = User.find_by_name!('Bob')
164
+
165
+ User.inactive.should == [bob]
166
+ User.linux.should == [anna]
167
+
168
+ User.with_sex.should == [anna]
169
+ User.without_sex.should == [bob]
170
+
171
+ User.public.should == [anna]
172
+ User.not_public.should == [bob]
173
+ end
174
+
175
+ describe "View helpers" do
176
+ include ActionView::Helpers::FormHelper
177
+ include ActionView::Helpers::FormOptionsHelper
178
+
179
+ before(:each) do
180
+ @options_status = [['Active', :active], ['Inactive', :inactive]]
181
+ @options_gui = [["cocoa", :cocoa], ["qt", :qt], ["gtk", :gtk]]
182
+ @options_so = [["Linux", :linux] , ["Mac OS X", :mac], ["Videogame", :win]]
183
+ end
184
+
185
+ it "test_helper_select_sym" do
186
+ @user.status = :inactive
187
+ output = "<select id=\"user_status\" name=\"user[status]\">#{options_for_select(@options_status, @user.status)}</select>"
188
+ output.should eql(select_sym("user", "status", nil))
189
+
190
+
191
+ output = "<select id=\"user_status\" name=\"user[status]\">#{options_for_select(@options_status, @user.status)}</select>"
192
+ output.should eql(select_sym("user", "status", nil))
193
+ end
194
+
195
+ def test_helper_select_sym_order
196
+ output_so = "<select id=\"user_so\" name=\"user[so]\">#{options_for_select(@options_so, @user.so)}</select>"
197
+ output_office = "<select id=\"user_office\" name=\"user[office]\">#{options_for_select(@options_office, @user.office)}</select>"
198
+
199
+ assert_equal output_so, select_sym("user", "so", nil)
200
+ assert_equal output_office, select_sym("user", "office", nil)
201
+ end
202
+
203
+ def test_helper_radio_sym
204
+ output = radio_sym("user", "status", nil)
205
+ assert_equal("<label>Active: <input checked=\"checked\" id=\"user_status_active\" name=\"user[status]\" type=\"radio\" value=\"active\" /></label><label>Inactive: <input id=\"user_status_inactive\" name=\"user[status]\" type=\"radio\" value=\"inactive\" /></label>", output)
206
+ end
207
+
208
+ end
209
+
210
+ describe "i18n" do
211
+
212
+ it "should test i18n ones" do
213
+ @user.language_text.should eql("Português")
214
+ end
215
+
216
+ it "should get the correct values" do
217
+ User.get_language_values.should =~ [["Português", :pt], ["Inglês", :en]]
218
+ end
219
+
220
+ it "should get the correct values" do
221
+ User::LANGUAGE_VALUES.should eql({:pt => "Português", :en => "Inglês"})
222
+ end
223
+
224
+ it "should test boolean" do
225
+ @user.sex_text.should eql("Feminino")
226
+ end
227
+
228
+ it "should get the correct values" do
229
+ User.get_sex_values.should eql([["Feminino", true],["Masculino", false]])
230
+ end
231
+
232
+ it "should get the correct values" do
233
+ User::SEX_VALUES.should eql({false=>"Masculino", true=>"Feminino"})
234
+ end
235
+
236
+ it "should translate a multiword class" do
237
+ @skill = UserSkill.create(:kind => :magic)
238
+ @skill.kind_text.should eql("Mágica")
239
+ end
240
+
241
+ end
242
+
243
+ describe "Methods" do
244
+
245
+ it "should play nice with other stuff" do
246
+ @user.karma.should be_nil
247
+ User::KARMA_VALUES.should eql({:bad => "bad", :ugly => "ugly", :good => "good"})
248
+ end
249
+
250
+ it "should provide a boolean method" do
251
+ @user.should_not be_good
252
+ @user.karma = :ugly
253
+ @user.should be_ugly
254
+ end
255
+
256
+ it "should work" do
257
+ @user.karma = "good"
258
+ @user.should be_good
259
+ @user.should_not be_bad
260
+ end
261
+
262
+ end
263
+
264
+ end
265
+
266
+ end
@@ -0,0 +1,59 @@
1
+ # Generated by jeweler
2
+ # DO NOT EDIT THIS FILE DIRECTLY
3
+ # Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
4
+ # -*- encoding: utf-8 -*-
5
+
6
+ Gem::Specification.new do |s|
7
+ s.name = %q{symbolize}
8
+ s.version = "1.1.0"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["Marcos Piccinini", "Martin Linkhorst"]
12
+ s.date = %q{2009-12-02}
13
+ s.description = %q{ActiveRecord enums with i18n}
14
+ s.email = %q{m.linkhorst@googlemail.com}
15
+ s.extra_rdoc_files = [
16
+ "README.rdoc"
17
+ ]
18
+ s.files = [
19
+ ".document",
20
+ ".gitignore",
21
+ "MIT-LICENSE",
22
+ "README.rdoc",
23
+ "Rakefile",
24
+ "VERSION",
25
+ "init.rb",
26
+ "lib/symbolize.rb",
27
+ "lib/symbolize_helper.rb",
28
+ "rails/init.rb",
29
+ "spec/db/create_testing_structure.rb",
30
+ "spec/locales/pt.yml",
31
+ "spec/spec_helper.rb",
32
+ "spec/symbolize_spec.rb",
33
+ "symbolize.gemspec"
34
+ ]
35
+ s.homepage = %q{http://github.com/linki/symbolize}
36
+ s.rdoc_options = ["--charset=UTF-8"]
37
+ s.require_paths = ["lib"]
38
+ s.rubygems_version = %q{1.3.5}
39
+ s.summary = %q{ActiveRecord enums with i18n}
40
+ s.test_files = [
41
+ "spec/db/create_testing_structure.rb",
42
+ "spec/spec_helper.rb",
43
+ "spec/symbolize_spec.rb"
44
+ ]
45
+
46
+ if s.respond_to? :specification_version then
47
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
48
+ s.specification_version = 3
49
+
50
+ if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
51
+ s.add_development_dependency(%q<rspec>, [">= 0"])
52
+ else
53
+ s.add_dependency(%q<rspec>, [">= 0"])
54
+ end
55
+ else
56
+ s.add_dependency(%q<rspec>, [">= 0"])
57
+ end
58
+ end
59
+
metadata ADDED
@@ -0,0 +1,82 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: linki-symbolize
3
+ version: !ruby/object:Gem::Version
4
+ version: 1.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Marcos Piccinini
8
+ - Martin Linkhorst
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+
13
+ date: 2009-12-02 00:00:00 +10:00
14
+ default_executable:
15
+ dependencies:
16
+ - !ruby/object:Gem::Dependency
17
+ name: rspec
18
+ type: :development
19
+ version_requirement:
20
+ version_requirements: !ruby/object:Gem::Requirement
21
+ requirements:
22
+ - - ">="
23
+ - !ruby/object:Gem::Version
24
+ version: "0"
25
+ version:
26
+ description: ActiveRecord enums with i18n
27
+ email: m.linkhorst@googlemail.com
28
+ executables: []
29
+
30
+ extensions: []
31
+
32
+ extra_rdoc_files:
33
+ - README.rdoc
34
+ files:
35
+ - .document
36
+ - .gitignore
37
+ - MIT-LICENSE
38
+ - README.rdoc
39
+ - Rakefile
40
+ - VERSION
41
+ - init.rb
42
+ - lib/symbolize.rb
43
+ - lib/symbolize_helper.rb
44
+ - linki-symbolize.gemspec
45
+ - rails/init.rb
46
+ - spec/db/create_testing_structure.rb
47
+ - spec/locales/pt.yml
48
+ - spec/spec_helper.rb
49
+ - spec/symbolize_spec.rb
50
+ - symbolize.gemspec
51
+ has_rdoc: true
52
+ homepage: http://github.com/linki/symbolize
53
+ licenses: []
54
+
55
+ post_install_message:
56
+ rdoc_options:
57
+ - --charset=UTF-8
58
+ require_paths:
59
+ - lib
60
+ required_ruby_version: !ruby/object:Gem::Requirement
61
+ requirements:
62
+ - - ">="
63
+ - !ruby/object:Gem::Version
64
+ version: "0"
65
+ version:
66
+ required_rubygems_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: "0"
71
+ version:
72
+ requirements: []
73
+
74
+ rubyforge_project:
75
+ rubygems_version: 1.3.5
76
+ signing_key:
77
+ specification_version: 3
78
+ summary: ActiveRecord enums with i18n
79
+ test_files:
80
+ - spec/db/create_testing_structure.rb
81
+ - spec/spec_helper.rb
82
+ - spec/symbolize_spec.rb