has_constant 0.2.0

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.
data/.document ADDED
@@ -0,0 +1,5 @@
1
+ README.rdoc
2
+ lib/**/*.rb
3
+ bin/*
4
+ features/**/*.feature
5
+ LICENSE
data/.gitignore ADDED
@@ -0,0 +1,22 @@
1
+ ## MAC OS
2
+ .DS_Store
3
+
4
+ ## TEXTMATE
5
+ *.tmproj
6
+ tmtags
7
+
8
+ ## EMACS
9
+ *~
10
+ \#*
11
+ .\#*
12
+
13
+ ## VIM
14
+ *.swp
15
+
16
+ ## PROJECT::GENERAL
17
+ coverage
18
+ rdoc
19
+ pkg
20
+ .bundle
21
+
22
+ ## PROJECT::SPECIFIC
data/.rvmrc ADDED
@@ -0,0 +1,2 @@
1
+ rvm use 1.8.7
2
+ rvm gemset use has_constant
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ source :gemcutter
2
+
3
+ group :test do
4
+ gem 'shoulda'
5
+ gem 'activesupport'
6
+ gem 'activerecord'
7
+ gem 'sqlite3-ruby'
8
+ end
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 mattbeedle
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.
data/README.rdoc ADDED
@@ -0,0 +1,17 @@
1
+ = has_constant
2
+
3
+ Description goes here.
4
+
5
+ == Note on Patches/Pull Requests
6
+
7
+ * Fork the project.
8
+ * Make your feature addition or bug fix.
9
+ * Add tests for it. This is important so I don't break it in a
10
+ future version unintentionally.
11
+ * Commit, do not mess with rakefile, version, or history.
12
+ (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
13
+ * Send me a pull request. Bonus points for topic branches.
14
+
15
+ == Copyright
16
+
17
+ Copyright (c) 2010 mattbeedle. See LICENSE for details.
data/Rakefile ADDED
@@ -0,0 +1,54 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+
4
+ begin
5
+ require 'jeweler'
6
+ Jeweler::Tasks.new do |gem|
7
+ gem.name = "has_constant"
8
+ gem.summary = %Q{Allows certain fields to be limited to a set of values}
9
+ gem.description = %Q{Allows certain fields to be limited to a set of values}
10
+ gem.email = "mattbeedle@gmail.com"
11
+ gem.homepage = "http://github.com/mattbeedle/has_constant"
12
+ gem.authors = ["mattbeedle"]
13
+ gem.add_development_dependency "shoulda", ">= 0"
14
+ gem.add_development_dependency 'activesupport', '>= 0'
15
+ # gem is a Gem::Specification... see http://www.rubygems.org/read/chapter/20 for additional settings
16
+ end
17
+ Jeweler::GemcutterTasks.new
18
+ rescue LoadError
19
+ puts "Jeweler (or a dependency) not available. Install it with: gem install jeweler"
20
+ end
21
+
22
+ require 'rake/testtask'
23
+ Rake::TestTask.new(:test) do |test|
24
+ test.libs << 'lib' << 'test'
25
+ test.pattern = 'test/**/*_test.rb'
26
+ test.verbose = true
27
+ end
28
+
29
+ begin
30
+ require 'rcov/rcovtask'
31
+ Rcov::RcovTask.new do |test|
32
+ test.libs << 'test'
33
+ test.pattern = 'test/**/test_*.rb'
34
+ test.verbose = true
35
+ end
36
+ rescue LoadError
37
+ task :rcov do
38
+ abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
39
+ end
40
+ end
41
+
42
+ task :test => :check_dependencies
43
+
44
+ task :default => :test
45
+
46
+ require 'rake/rdoctask'
47
+ Rake::RDocTask.new do |rdoc|
48
+ version = File.exist?('VERSION') ? File.read('VERSION') : ""
49
+
50
+ rdoc.rdoc_dir = 'rdoc'
51
+ rdoc.title = "has_constant #{version}"
52
+ rdoc.rdoc_files.include('README*')
53
+ rdoc.rdoc_files.include('lib/**/*.rb')
54
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.2.0
@@ -0,0 +1,65 @@
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{has_constant}
8
+ s.version = "0.2.0"
9
+
10
+ s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
+ s.authors = ["mattbeedle"]
12
+ s.date = %q{2010-07-26}
13
+ s.description = %q{Allows certain fields to be limited to a set of values}
14
+ s.email = %q{mattbeedle@gmail.com}
15
+ s.extra_rdoc_files = [
16
+ "LICENSE",
17
+ "README.rdoc"
18
+ ]
19
+ s.files = [
20
+ ".document",
21
+ ".gitignore",
22
+ ".rvmrc",
23
+ "Gemfile",
24
+ "LICENSE",
25
+ "README.rdoc",
26
+ "Rakefile",
27
+ "VERSION",
28
+ "has_constant.gemspec",
29
+ "lib/has_constant.rb",
30
+ "lib/orm/active_record.rb",
31
+ "lib/orm/mongoid.rb",
32
+ "test/has_constant_test.rb",
33
+ "test/helper.rb",
34
+ "test/unit/orm/active_record_test.rb",
35
+ "test/unit/orm/mongoid_test.rb"
36
+ ]
37
+ s.homepage = %q{http://github.com/mattbeedle/has_constant}
38
+ s.rdoc_options = ["--charset=UTF-8"]
39
+ s.require_paths = ["lib"]
40
+ s.rubygems_version = %q{1.3.7}
41
+ s.summary = %q{Allows certain fields to be limited to a set of values}
42
+ s.test_files = [
43
+ "test/has_constant_test.rb",
44
+ "test/helper.rb",
45
+ "test/unit/orm/active_record_test.rb",
46
+ "test/unit/orm/mongoid_test.rb"
47
+ ]
48
+
49
+ if s.respond_to? :specification_version then
50
+ current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
51
+ s.specification_version = 3
52
+
53
+ if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
54
+ s.add_development_dependency(%q<shoulda>, [">= 0"])
55
+ s.add_development_dependency(%q<activesupport>, [">= 0"])
56
+ else
57
+ s.add_dependency(%q<shoulda>, [">= 0"])
58
+ s.add_dependency(%q<activesupport>, [">= 0"])
59
+ end
60
+ else
61
+ s.add_dependency(%q<shoulda>, [">= 0"])
62
+ s.add_dependency(%q<activesupport>, [">= 0"])
63
+ end
64
+ end
65
+
@@ -0,0 +1,61 @@
1
+ require 'lib/orm/mongoid'
2
+ require 'lib/orm/active_record'
3
+ require 'active_support/inflector'
4
+ module HasConstant
5
+
6
+ def self.included(base)
7
+ base.extend(ClassMethods)
8
+ end
9
+
10
+ # HasConstant takes a Proc containing an array of possible values for a field name
11
+ # The field name is inferred as the singular of the has constant name. For example
12
+ # has_constant :titles
13
+ # would use the database column "title"
14
+ #
15
+ # USAGE:
16
+ #
17
+ # class User < ActiveRecord::Base
18
+ # include HasConstant
19
+ # has_constant :titles, lambda { %w(Mr Mrs) }
20
+ # end
21
+ #
22
+ # User.titles #=> ['Mr', 'Ms']
23
+ #
24
+ # @user = User.new(:title => 'Mr')
25
+ # @user.title #=> 'Mr'
26
+ # @user.attributes['title'] #=> 0
27
+ #
28
+ # @user.title_is?('Mr') #=> true
29
+ # @user.title_is?('Ms') #=> false
30
+ #
31
+ # User.by_constant('title', 'Mr') #=> [@user]
32
+ #
33
+ module ClassMethods
34
+ def has_constant(name, values, options = {})
35
+
36
+ singular = (options[:accessor] || name.to_s.singularize).to_s
37
+
38
+ (class << self; self; end).instance_eval do
39
+ define_method(name.to_s, values) if values.respond_to?(:call)
40
+ define_method(name.to_s, lambda { values }) unless values.respond_to?(:call)
41
+ end
42
+
43
+ define_method(singular) do
44
+ values[instance_variable_get("@#{singular}")]
45
+ end
46
+
47
+ # Add the setter method. This takes the string representation and converts it to an integer to store in the DB
48
+ define_method("#{singular}=") do |val|
49
+ if val.instance_of?(String)
50
+ instance_variable_set("@#{singular}", values.index(val))
51
+ else
52
+ instance_variable_set("@#{singular}", val)
53
+ end
54
+ end
55
+
56
+ define_method("#{singular}_is?") do |value|
57
+ eval("#{singular} == '#{value.to_s}'")
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,46 @@
1
+ module HasConstant
2
+ module Orm
3
+ module ActiveRecord
4
+ def self.included( base )
5
+ base.extend(ClassMethods)
6
+ end
7
+
8
+ module ClassMethods
9
+ def has_constant( name, values, options = {} )
10
+ super(name, values, options)
11
+
12
+ singular = (options[:accessor] || name.to_s.singularize).to_s
13
+
14
+ # Add the getter method. This returns the string representation of the stored value
15
+ define_method(singular) do
16
+ self.class.send(name)[read_attribute(singular).to_i] if read_attribute(singular)
17
+ end
18
+
19
+ define_method("#{singular}=") do |val|
20
+ if val.instance_of?(String)
21
+ write_attribute singular.to_sym, self.class.send(name.to_s).index(val)
22
+ else
23
+ write_attribute singular.to_sym, val
24
+ end
25
+ end
26
+
27
+ class_eval do
28
+ named_scope :by_constant, lambda { |constant,value| { :conditions =>
29
+ { constant.to_sym => eval("#{self.to_s}.#{constant.pluralize}.index(value)") } } }
30
+ named_scope "#{singular}_is".to_sym, lambda { |*values| { :conditions =>
31
+ { singular.to_sym => indexes_for(name, values) }
32
+ } }
33
+ named_scope "#{singular}_is_not".to_sym, lambda { |*values| { :conditions =>
34
+ ["#{singular} NOT IN (?)", indexes_for(name, values)]
35
+ } }
36
+ end
37
+ end
38
+
39
+ private
40
+ def indexes_for( name, values )
41
+ values.map { |v| self.send(name.to_sym).index(v) }
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,39 @@
1
+ module HasConstant
2
+ module Orm
3
+ module Mongoid
4
+ def self.included( base )
5
+ base.extend(ClassMethods)
6
+ end
7
+
8
+ module ClassMethods
9
+ def has_constant( name, values, options = {} )
10
+ super(name, values, options)
11
+
12
+ singular = (options[:accessor] || name.to_s.singularize).to_s
13
+
14
+ # Add the getter method. This returns the string representation of the stored value
15
+ define_method(singular) do
16
+ eval("#{self.class}.#{name.to_s}[self.attributes[singular].to_i] if self.attributes[singular]")
17
+ end
18
+
19
+ define_method("#{singular}=") do |val|
20
+ if val.instance_of?(String)
21
+ write_attribute singular.to_sym, self.class.send(name.to_s).index(val)
22
+ else
23
+ write_attribute singular.to_sym, val
24
+ end
25
+ end
26
+
27
+ class_eval do
28
+ named_scope :by_constant, lambda { |constant,value| { :where =>
29
+ { constant.to_sym => eval("#{self.to_s}.#{constant.pluralize}.index(value)") } } }
30
+ named_scope "#{singular}_is".to_sym, lambda { |*values| { :where =>
31
+ { singular.to_sym => { '$in' => values.map { |v| self.send(name.to_sym).index(v) } } } } }
32
+ named_scope "#{singular}_is_not".to_sym, lambda { |*values| { :where =>
33
+ { singular.to_sym => { '$nin' => values.map { |v| self.send(name.to_sym).index(v) } } } } }
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,44 @@
1
+ require 'helper'
2
+
3
+ class Model
4
+ include HasConstant
5
+
6
+ attr_accessor :salutation
7
+ end
8
+
9
+ class TestHasConstant < Test::Unit::TestCase
10
+ should 'default accessor to singular of the constant name' do
11
+ Model.has_constant :titles, ['Mr', 'Mrs']
12
+ assert Model.new.respond_to?(:title)
13
+ assert Model.new.respond_to?(:title=)
14
+ end
15
+
16
+ should 'be able to override accessor' do
17
+ Model.has_constant :titles, ['Mr', 'Mrs'], :accessor => :salutation
18
+ m = Model.new
19
+ m.salutation = 'Mr'
20
+ assert_equal 'Mr', m.salutation
21
+ end
22
+
23
+ should 'be able to use an array' do
24
+ Model.has_constant :titles, ['Mr', 'Mrs']
25
+ assert_equal ['Mr', 'Mrs'], Model.titles
26
+ end
27
+
28
+ should 'be able to use a proc' do
29
+ Model.has_constant :titles, Proc.new { ['Mr', 'Mrs'] }
30
+ assert_equal ['Mr', 'Mrs'], Model.titles
31
+ end
32
+
33
+ should 'be able to use lambda' do
34
+ Model.has_constant :titles, lambda { ['Mr', 'Mrs'] }
35
+ assert_equal ['Mr', 'Mrs'], Model.titles
36
+ end
37
+
38
+ should 'provide singular_is? comparison method' do
39
+ Model.has_constant :titles, ['Mr', 'Mrs']
40
+ m = Model.new
41
+ m.title = 'Mr'
42
+ assert m.title_is?('Mr')
43
+ end
44
+ end
data/test/helper.rb ADDED
@@ -0,0 +1,56 @@
1
+ require 'rubygems'
2
+ require 'test/unit'
3
+ require 'shoulda'
4
+
5
+ $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
6
+ $LOAD_PATH.unshift(File.dirname(__FILE__))
7
+ require 'has_constant'
8
+
9
+ def setup_mongoid
10
+ begin
11
+ require 'mongoid'
12
+ Mongoid.database = Mongo::Connection.new('localhost', @port).db('i18n_test')
13
+ rescue LoadError => e
14
+ puts "can't use Mongoid adapter because: #{e}"
15
+ end
16
+ end
17
+
18
+ def setup_active_record
19
+ begin
20
+ require 'active_record'
21
+ ActiveRecord::Base.connection
22
+ true
23
+ rescue LoadError => e
24
+ puts "can't use ActiveRecord backend because: #{e.message}"
25
+ rescue ActiveRecord::ConnectionNotEstablished
26
+ connect_active_record
27
+ true
28
+ end
29
+ end
30
+
31
+ def connect_active_record
32
+ connect_adapter
33
+ ActiveRecord::Migration.verbose = false
34
+ ActiveRecord::Schema.define(:version => 1) do
35
+ create_table :users, :force => true do |t|
36
+ t.integer :salutation
37
+ end
38
+ end
39
+ end
40
+
41
+ def connect_adapter
42
+ ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ":memory:")
43
+ end
44
+
45
+ class Test::Unit::TestCase
46
+
47
+ def setup
48
+ Mongoid.database.collections.each do |collection|
49
+ begin
50
+ collection.drop
51
+ rescue
52
+ end
53
+ end if defined?(Mongoid)
54
+ User.delete_all if defined?(ActiveRecord)
55
+ end
56
+ end
@@ -0,0 +1,41 @@
1
+ require 'helper'
2
+
3
+ setup_active_record
4
+
5
+ class User < ActiveRecord::Base
6
+ include HasConstant
7
+ include HasConstant::Orm::ActiveRecord
8
+
9
+ has_constant :salutations, ['Mr', 'Mrs']
10
+ end if defined?(ActiveRecord)
11
+
12
+ class ActiveRecordTest < Test::Unit::TestCase
13
+ should 'save values as integers' do
14
+ u = User.new(:salutation => 'Mr')
15
+ u.save!
16
+ assert_equal 'Mr', u.salutation
17
+ assert_equal 0, u.attributes['salutation']
18
+ end
19
+
20
+ context 'scopes' do
21
+ setup do
22
+ @man = User.create!(:salutation => 'Mr')
23
+ @woman = User.create!(:salutation => 'Mrs')
24
+ end
25
+
26
+ should 'provide by_constant scope' do
27
+ assert_equal 1, User.by_constant('salutation', 'Mr').count
28
+ assert_equal @man, User.by_constant('salutation', 'Mr').first
29
+ end
30
+
31
+ should 'provide singular_is scope' do
32
+ assert_equal 1, User.salutation_is('Mr').count
33
+ assert_equal @man, User.salutation_is('Mr').first
34
+ end
35
+
36
+ should 'provide singular_is_not scope' do
37
+ assert_equal 1, User.salutation_is_not('Mr').count
38
+ assert_equal @woman, User.salutation_is_not('Mr').first
39
+ end
40
+ end
41
+ end if defined?(ActiveRecord)
@@ -0,0 +1,44 @@
1
+ require 'helper'
2
+
3
+ setup_mongoid
4
+
5
+ class MongoUser
6
+ include Mongoid::Document
7
+ include HasConstant
8
+ include HasConstant::Orm::Mongoid
9
+
10
+ field :salutation, :type => Integer
11
+
12
+ has_constant :salutations, ['Mr', 'Mrs']
13
+ end if defined?(Mongoid)
14
+
15
+ class MongoidTest < Test::Unit::TestCase
16
+ should 'save values as integers' do
17
+ m = MongoUser.new(:salutation => 'Mr')
18
+ m.save!
19
+ assert_equal 'Mr', m.salutation
20
+ assert_equal 0, m.attributes['salutation']
21
+ end
22
+
23
+ context 'scopes' do
24
+ setup do
25
+ @man = MongoUser.create!(:salutation => 'Mr')
26
+ @woman = MongoUser.create!(:salutation => 'Mrs')
27
+ end
28
+
29
+ should 'provide by_constant scope' do
30
+ assert_equal 1, MongoUser.by_constant('salutation', 'Mr').count
31
+ assert_equal @man, MongoUser.by_constant('salutation', 'Mr').first
32
+ end
33
+
34
+ should 'provide singular_is scope' do
35
+ assert_equal 1, MongoUser.salutation_is('Mr').count
36
+ assert_equal @man, MongoUser.salutation_is('Mr').first
37
+ end
38
+
39
+ should 'provide singular_is_not scope' do
40
+ assert_equal 1, MongoUser.salutation_is_not('Mr').count
41
+ assert_equal @woman, MongoUser.salutation_is_not('Mr').first
42
+ end
43
+ end
44
+ end if defined?(Mongoid)
metadata ADDED
@@ -0,0 +1,113 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: has_constant
3
+ version: !ruby/object:Gem::Version
4
+ hash: 23
5
+ prerelease: false
6
+ segments:
7
+ - 0
8
+ - 2
9
+ - 0
10
+ version: 0.2.0
11
+ platform: ruby
12
+ authors:
13
+ - mattbeedle
14
+ autorequire:
15
+ bindir: bin
16
+ cert_chain: []
17
+
18
+ date: 2010-07-26 00:00:00 +02:00
19
+ default_executable:
20
+ dependencies:
21
+ - !ruby/object:Gem::Dependency
22
+ name: shoulda
23
+ prerelease: false
24
+ requirement: &id001 !ruby/object:Gem::Requirement
25
+ none: false
26
+ requirements:
27
+ - - ">="
28
+ - !ruby/object:Gem::Version
29
+ hash: 3
30
+ segments:
31
+ - 0
32
+ version: "0"
33
+ type: :development
34
+ version_requirements: *id001
35
+ - !ruby/object:Gem::Dependency
36
+ name: activesupport
37
+ prerelease: false
38
+ requirement: &id002 !ruby/object:Gem::Requirement
39
+ none: false
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ hash: 3
44
+ segments:
45
+ - 0
46
+ version: "0"
47
+ type: :development
48
+ version_requirements: *id002
49
+ description: Allows certain fields to be limited to a set of values
50
+ email: mattbeedle@gmail.com
51
+ executables: []
52
+
53
+ extensions: []
54
+
55
+ extra_rdoc_files:
56
+ - LICENSE
57
+ - README.rdoc
58
+ files:
59
+ - .document
60
+ - .gitignore
61
+ - .rvmrc
62
+ - Gemfile
63
+ - LICENSE
64
+ - README.rdoc
65
+ - Rakefile
66
+ - VERSION
67
+ - has_constant.gemspec
68
+ - lib/has_constant.rb
69
+ - lib/orm/active_record.rb
70
+ - lib/orm/mongoid.rb
71
+ - test/has_constant_test.rb
72
+ - test/helper.rb
73
+ - test/unit/orm/active_record_test.rb
74
+ - test/unit/orm/mongoid_test.rb
75
+ has_rdoc: true
76
+ homepage: http://github.com/mattbeedle/has_constant
77
+ licenses: []
78
+
79
+ post_install_message:
80
+ rdoc_options:
81
+ - --charset=UTF-8
82
+ require_paths:
83
+ - lib
84
+ required_ruby_version: !ruby/object:Gem::Requirement
85
+ none: false
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ hash: 3
90
+ segments:
91
+ - 0
92
+ version: "0"
93
+ required_rubygems_version: !ruby/object:Gem::Requirement
94
+ none: false
95
+ requirements:
96
+ - - ">="
97
+ - !ruby/object:Gem::Version
98
+ hash: 3
99
+ segments:
100
+ - 0
101
+ version: "0"
102
+ requirements: []
103
+
104
+ rubyforge_project:
105
+ rubygems_version: 1.3.7
106
+ signing_key:
107
+ specification_version: 3
108
+ summary: Allows certain fields to be limited to a set of values
109
+ test_files:
110
+ - test/has_constant_test.rb
111
+ - test/helper.rb
112
+ - test/unit/orm/active_record_test.rb
113
+ - test/unit/orm/mongoid_test.rb