Compare commits

..

41 Commits

Author SHA1 Message Date
599e82a106 upversioned 2023-01-12 20:25:24 +01:00
6eea09d8eb upversioned mongoid 2023-01-12 20:21:09 +01:00
de414b0ee7 upversioned 2023-01-12 20:17:19 +01:00
Nicholas Bruning
b57fb616cb Version bump to 0.4.0 2015-11-10 16:07:54 +11:00
Nicholas Bruning
0ae62f1816 Merge pull request #24 from 90yukke/support-mognoid-5
Update required major version of mongoid to 5
2015-11-10 16:03:19 +11:00
Alexander Karmes
589b5598a4 Remove database-cleaner.
- It was not able to work with mongoid 5
- I don't see the reason to use both Mongoid.purge! and
  DatabaseCleaner.truncate! It looks like doing double work
2015-09-17 03:21:30 +02:00
Alexander Karmes
546fc91cb1 Change configuration of Mongoid.
By default mongoid use verbose logging, so I changed log level to :info
Also mongoid config renamed "sessions" method to "cliens" and hence I
renamed key in mongoid.yml
2015-09-17 03:14:03 +02:00
Alexander Karmes
b902d662c6 Set required major version of mongoid-rspec to 3 2015-09-17 03:13:26 +02:00
Alexander Karmes
75822dae4f Update required major version of mongoid to 5 2015-09-16 23:06:45 +02:00
Nicholas Bruning
2288ee6cec Removed aliasing and replaced with explicit accessors
* Added casting from String -> Symbol on setter

Closes #9
2015-07-22 16:13:43 +10:00
Nicholas Bruning
1c3d10e407 Added spec coverage for required values. Refer #7 2015-07-22 14:58:04 +10:00
Nicholas Bruning
288bfcc978 Added Guardfile, updated development dependencies 2015-07-22 14:57:46 +10:00
Nicholas Bruning
3429216331 Version bump to 0.3.0
Adds configuration option for `field_name_prefix` allowing for
removal of leading underscores on field names.

Closes #12
2015-07-22 14:35:01 +10:00
Nicholas Bruning
781f05f707 Merge pull request #16 from glooko/customizable_field_prefix
Customizable field name prefix
2015-07-22 14:32:17 +10:00
Kristijan Novoselić
c2f9bfda27 Fixed formatting issues 2015-03-17 15:11:50 +01:00
Kristijan Novoselić
5a956c67e2 Field prefix is now configurable 2015-03-17 14:47:46 +01:00
Kristijan Novoselić
1f43e0d4d8 Got rid of deprecation messages due to usage of be_true and be_false 2015-03-17 14:15:41 +01:00
Nicholas Bruning
a04acec0da Version bump to 0.2.0 2014-07-12 13:32:20 +10:00
Nicholas Bruning
a0892df6d5 Merged plainprogrammer-feature-mongoid4 2014-07-12 13:31:45 +10:00
Nicholas Bruning
a0ebd468aa Merge branch 'plainprogrammer-feature-mongoid4' 2014-07-12 13:30:03 +10:00
Nicholas Bruning
7e62ee3e06 Updated gitignore, travis build matrix and cleaned up gemspecs 2014-07-12 13:19:02 +10:00
Nicholas Bruning
db0901e6f1 Removed RBX from travis matrix 2014-07-12 12:39:22 +10:00
Nicholas Bruning
3fda46a9a8 Merge pull request #10 from tkrajcar/master
Add README information on setting default values for enums with multiple values.
2014-05-31 20:53:04 +10:00
Tim Krajcar
97bc810bff Add information on setting default values for enums with multiple values. 2014-05-30 19:47:04 -07:00
Nicholas Bruning
fd8063da6d Update README.md 2014-04-19 19:03:37 +10:00
Nicholas Bruning
d07e5c55be Update README.md 2014-04-19 19:01:56 +10:00
Nicholas Bruning
8b5b23bb45 Merge pull request #5 from thetron/update/cleanup
Quest for the 4.0 GPA
2014-03-18 00:08:59 +11:00
Nicholas Bruning
42cd5a0d51 Tweaked accessors conditional 2014-03-18 00:02:24 +11:00
Nicholas Bruning
58825a4f20 Added ruby 2.1.1 to travis config 2014-03-17 23:48:38 +11:00
Nicholas Bruning
41c95e0370 Updated travis config, removed RBX and notifications 2014-03-17 23:48:01 +11:00
Nicholas Bruning
fde35639d8 Refactored accessor definition into methods 2014-03-17 23:44:40 +11:00
Nicholas Bruning
d4280d3eca Refactored Mongoid::Enum::ClassMethods for readability 2014-03-17 23:35:39 +11:00
Nicholas Bruning
9144fab09a Added Code Climate badge 2014-03-17 23:35:03 +11:00
Nicholas Bruning
eda65ef33d Merge branch 'feature-mongoid4' of git://github.com/plainprogrammer/mongoid-enum into plainprogrammer-feature-mongoid4 2014-03-17 22:40:23 +11:00
James Thompson
6dbc5a459f Wrapped scope condition in proc. 2014-02-10 11:03:27 -07:00
Nicholas Bruning
80f8941e05 Merge pull request #2 from simi/patch-1
Update README.md
2013-11-15 14:35:13 -08:00
Josef Šimánek
b7166acdbe Update README.md
better ruby GH markup
[ci skip]
2013-11-12 02:16:54 +01:00
James Thompson
40ffdbd864 Added Mongoid4.gemfile.lock to ignore list. 2013-11-10 09:32:21 -07:00
James Thompson
8c0f386b3a Added custom gemfile for Mongoid 4 and updated Gemspec to allow for Mongoid 4. 2013-11-10 09:20:16 -07:00
James Thompson
011433b3ee Updated build configuration. 2013-11-10 09:19:45 -07:00
Nicholas Bruning
316ba49db4 Update README.md 2013-11-07 11:48:07 +11:00
13 changed files with 271 additions and 81 deletions

1
.gitignore vendored
View File

@ -15,3 +15,4 @@ spec/reports
test/tmp
test/version_tmp
tmp
.idea

View File

@ -1,14 +1,14 @@
script: "bundle exec rspec spec"
language: ruby
rvm:
- 1.9.3
- 2.0.0
- 2.1.0
- 2.1.1
- 2.1.2
- jruby-19mode
- rbx-19mode
gemfile:
- Gemfile
notifications:
recipients:
- nicholas@bruning.com.au
services:
- mongodb

8
Guardfile Normal file
View File

@ -0,0 +1,8 @@
# A sample Guardfile
# More info at https://github.com/guard/guard#readme
guard :rspec, cmd: "bundle exec rspec" do
watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| "spec/lib/#{m[1]}_spec.rb" }
watch('spec/spec_helper.rb') { "spec" }
end

View File

@ -2,6 +2,7 @@
[![Build
Status](https://travis-ci.org/thetron/mongoid-enum.png)](https://travis-ci.org/thetron/mongoid-enum)
[![Code Climate](https://codeclimate.com/github/thetron/mongoid-enum.png)](https://codeclimate.com/github/thetron/mongoid-enum)
Heavily inspired by [DHH's
ActiveRecord::Enum](https://github.com/rails/rails/commit/db41eb8a6ea88b854bf5cd11070ea4245e1639c5), this little library is
@ -16,25 +17,27 @@ and a few other bits-and-bobs.
Add this to your Gemfile:
gem "mongoid-enum"
```ruby
gem "mongoid-enum"
```
And then run `bundle install`.
# Usage
````
```ruby
class Payment
include Mongoid::Document
include Mongoid::Enum
enum :status, [:pending, :approved, :declined],
enum :status, [:pending, :approved, :declined]
end
````
```
Aaaaaaand then you get things like:
````
```ruby
payment = Payment.create
payment.status
@ -49,7 +52,7 @@ payment.pending?
Payment.approved
# => Mongoid::Criteria for payments with status == :approved
````
```
# Features
@ -64,13 +67,13 @@ convenience.
## Accessors
Your enums will get getters-and-setters with the same name. So using the
'Payment' example above:
`Payment` example above:
````
```ruby
payment.status = :declined
payment.status
# => :declined
````
```
And you also get bang(!) and query(?) methods for each of the values in
your enum (see [this example](#usage).
@ -82,10 +85,10 @@ For each enum, you'll also get a constant named after it. This is to
help you elsewhere in your app, should you need to display, or leverage
the list of values. Using the above example:
````
```ruby
Payment::STATUS
# => [:pending, :approved, :declined]
````
```
## Validations
@ -99,11 +102,11 @@ disable this behaviour (see [below](#options)).
A scope added for each of your enum's values. Using the example above,
you'd automatically get:
````
```ruby
Payment.pending # => Mongoid::Criteria
Payment.approved # => Mongoid::Criteria
Payment.declined # => Mongoid::Criteria
````
```
# Options
@ -114,25 +117,37 @@ If not specified, the default will be the first in your list of values
(`:pending` in the example above). You can override this with the
`:default` option:
enum :roles, [:manager, :administrator], :default => ""
```ruby
enum :roles, [:manager, :administrator], :default => ""
```
## Multiple values
Sometimes you'll need to store multiple values from your list, this
couldn't be easier:
enum, :roles => [:basic, :manager, :administrator], :multiple => true
```ruby
enum :roles, [:basic, :manager, :administrator], :multiple => true
user = User.create
user.roles << :basic
user.roles << :manager
user.save!
# ...
user.manager? # => true
user.administrator? # => false
user.roles # => [:basic, :manager]
user = User.create
user.roles << :basic
user.roles << :manager
user.save!
user.manager? # => true
user.administrator? # => false
user.roles # => [:basic, :manager]
```
Since the underlying datatype for storing values is an array, if you
need to specify default(s), ensure you use an array:
```ruby
enum :roles, [:noob, :author, :editor], :multiple => true, :default => [:author, :editor] # two defaults
enum :roles, [:noob, :author, :editor], :multiple => true, :default => [] # no default
```
## Validations
@ -141,8 +156,9 @@ your field are always from your list of options. If you need more
complex validations, or you just want to throw caution to the wind, you
can turn them off:
enum :status => [:up, :down], :validate => false
```ruby
enum :status, [:up, :down], :validate => false
```
# Issues and Feature Requests

View File

@ -1,42 +1,93 @@
require "mongoid/enum/version"
require "mongoid/enum/validators/multiple_validator"
require "mongoid/enum/configuration"
module Mongoid
module Enum
extend ActiveSupport::Concern
module ClassMethods
def enum(name, values, options = {})
field_name = :"_#{name}"
field_name = :"#{Mongoid::Enum.configuration.field_name_prefix}#{name}"
options = default_options(values).merge(options)
set_values_constant name, values
create_field field_name, options
create_validations field_name, values, options
define_value_scopes_and_accessors field_name, values, options
define_field_accessor name, field_name, options
end
private
def default_options(values)
{
:multiple => false,
:default => values.first,
:required => true,
:validate => true
}
end
def set_values_constant(name, values)
const_name = name.to_s.upcase
multiple = options[:multiple] || false
default = options[:default].nil? && values.first || options[:default]
required = options[:required].nil? || options[:required]
validate = options[:validate].nil? || options[:validate]
const_set const_name, values
end
type = multiple && Array || Symbol
field field_name, :type => type, :default => default
alias_attribute name, field_name
def create_field(field_name, options)
type = options[:multiple] && Array || Symbol
field field_name, :type => type, :default => options[:default]
end
if multiple && validate
validates field_name, :'mongoid/enum/validators/multiple' => { :in => values, :allow_nil => !required }
def create_validations(field_name, values, options)
if options[:multiple] && options[:validate]
validates field_name, :'mongoid/enum/validators/multiple' => { :in => values.map(&:to_sym), :allow_nil => !options[:required] }
#FIXME: Shouldn't this be `elsif options[:validate]` ???
elsif validate
validates field_name, :inclusion => {:in => values}, :allow_nil => !required
validates field_name, :inclusion => {:in => values.map(&:to_sym)}, :allow_nil => !options[:required]
end
end
def define_value_scopes_and_accessors(field_name, values, options)
values.each do |value|
scope value, where(field_name => value)
scope value, ->{ where(field_name => value) }
if multiple
class_eval "def #{value}?() self.#{field_name}.include?(:#{value}) end"
class_eval "def #{value}!() update_attributes! :#{field_name} => (self.#{field_name} || []) + [:#{value}] end"
if options[:multiple]
define_array_accessor(field_name, value)
else
class_eval "def #{value}?() self.#{field_name} == :#{value} end"
class_eval "def #{value}!() update_attributes! :#{field_name} => :#{value} end"
define_string_accessor(field_name, value)
end
end
end
def define_field_accessor(name, field_name, options)
if options[:multiple]
define_array_field_accessor name, field_name
else
define_string_field_accessor name, field_name
end
end
def define_array_field_accessor(name, field_name)
class_eval "def #{name}=(vals) self.write_attribute(:#{field_name}, Array(vals).compact.map(&:to_sym)) end"
class_eval "def #{name}() self.read_attribute(:#{field_name}) end"
end
def define_string_field_accessor(name, field_name)
class_eval "def #{name}=(val) self.write_attribute(:#{field_name}, val && val.to_sym || nil) end"
class_eval "def #{name}() self.read_attribute(:#{field_name}) end"
end
def define_array_accessor(field_name, value)
class_eval "def #{value}?() self.#{field_name}.include?(:#{value}) end"
class_eval "def #{value}!() update_attributes! :#{field_name} => (self.#{field_name} || []) + [:#{value}] end"
end
def define_string_accessor(field_name, value)
class_eval "def #{value}?() self.#{field_name} == :#{value} end"
class_eval "def #{value}!() update_attributes! :#{field_name} => :#{value} end"
end
end
end
end

View File

@ -0,0 +1,19 @@
module Mongoid
module Enum
class Configuration
attr_accessor :field_name_prefix
def initialize
self.field_name_prefix = "_"
end
end
def self.configuration
@configuration ||= Configuration.new
end
def self.configure
yield(configuration) if block_given?
end
end
end

View File

@ -1,5 +1,5 @@
module Mongoid
module Enum
VERSION = "0.1.1"
VERSION = "0.4.6"
end
end

View File

@ -6,11 +6,11 @@ require 'mongoid/enum/version'
Gem::Specification.new do |spec|
spec.name = "mongoid-enum"
spec.version = Mongoid::Enum::VERSION
spec.authors = ["Nicholas Bruning"]
spec.email = ["nicholas@bruning.com.au"]
spec.description = %q{Heavily inspired by DDH's ActiveRecord::Enum, this little library is there to help you cut down the cruft in your models and make the world a happier place at the same time.}
spec.authors = ["Mike Sutton"]
spec.email = ["tech@wizewerx.com"]
spec.description = %q{Forked from https://github.com/thetron/mongoid-enum/commits?author=thetron.}
spec.summary = %q{Sweet enum sugar for your Mongoid documents}
spec.homepage = "https://github.com/thetron/mongoid-enum"
spec.homepage = "https://git.wizewerx.tech/foss/mongoid-enum"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
@ -18,12 +18,10 @@ Gem::Specification.new do |spec|
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency "mongoid", "~>3.1"
spec.add_runtime_dependency "mongoid", "~> 8.0"
spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 2.14"
spec.add_development_dependency "guard-rspec", "~> 4.0.3"
spec.add_development_dependency "database_cleaner", "~> 1.2.0"
spec.add_development_dependency "mongoid-rspec", "~> 1.5.1"
spec.add_development_dependency "rspec", "~> 3.1"
spec.add_development_dependency "guard-rspec", "~> 4.6.2"
spec.add_development_dependency "mongoid-rspec", "~> 3.0"
end

View File

@ -0,0 +1,11 @@
require 'spec_helper'
describe Mongoid::Enum::Configuration do
subject { Mongoid::Enum::Configuration.new }
describe "field_name_prefix" do
it "has '_' as default value" do
expect(subject.field_name_prefix).to eq "_"
end
end
end

View File

@ -16,14 +16,14 @@ describe Mongoid::Enum::Validators::MultipleValidator do
context "and value is nil" do
before(:each) { validator.validate_each(record, attribute, nil) }
it "validates" do
expect(record.errors[attribute].empty?).to be_true
expect(record.errors[attribute].empty?).to be true
end
end
context "and value is []" do
before(:each) { validator.validate_each(record, attribute, []) }
it "validates" do
expect(record.errors[attribute].empty?).to be_true
expect(record.errors[attribute].empty?).to be true
end
end
end
@ -32,14 +32,14 @@ describe Mongoid::Enum::Validators::MultipleValidator do
context "and value is nil" do
before(:each) { validator.validate_each(record, attribute, nil) }
it "won't validate" do
expect(record.errors[attribute].any?).to be_true
expect(record.errors[attribute].any?).to be true
expect(record.errors[attribute]).to eq ["is not in #{values.join ", "}"]
end
end
context "and value is []" do
before(:each) { validator.validate_each(record, attribute, []) }
it "won't validate" do
expect(record.errors[attribute].any?).to be_true
expect(record.errors[attribute].any?).to be true
expect(record.errors[attribute]).to eq ["is not in #{values.join ", "}"]
end
end
@ -49,7 +49,7 @@ describe Mongoid::Enum::Validators::MultipleValidator do
let(:allow_nil) { rand(2).zero? }
before(:each) { validator.validate_each(record, attribute, [values.sample]) }
it "validates" do
expect(record.errors[attribute].empty?).to be_true
expect(record.errors[attribute].empty?).to be true
end
end
@ -57,7 +57,7 @@ describe Mongoid::Enum::Validators::MultipleValidator do
let(:allow_nil) { rand(2).zero? }
before(:each) { validator.validate_each(record, attribute, [:amet]) }
it "won't validate" do
expect(record.errors[attribute].any?).to be_true
expect(record.errors[attribute].any?).to be true
end
end
@ -65,7 +65,7 @@ describe Mongoid::Enum::Validators::MultipleValidator do
let(:allow_nil) { rand(2).zero? }
before(:each) { validator.validate_each(record, attribute, [values.first, values.last]) }
it "validates" do
expect(record.errors[attribute].empty?).to be_true
expect(record.errors[attribute].empty?).to be true
end
end
@ -73,7 +73,7 @@ describe Mongoid::Enum::Validators::MultipleValidator do
let(:allow_nil) { rand(2).zero? }
before(:each) { validator.validate_each(record, attribute, [values.first, values.last, :amet]) }
it "won't validate" do
expect(record.errors[attribute].any?).to be_true
expect(record.errors[attribute].any?).to be true
end
end
end

View File

@ -1,4 +1,5 @@
require 'spec_helper'
require 'mongoid/enum/configuration'
class User
include Mongoid::Document
@ -21,10 +22,27 @@ describe Mongoid::Enum do
expect(klass).to have_field(field_name)
end
it "uses prefix defined in configuration" do
old_field_name_prefix = Mongoid::Enum.configuration.field_name_prefix
Mongoid::Enum.configure do |config|
config.field_name_prefix = "___"
end
UserWithoutPrefix = Class.new do
include Mongoid::Document
include Mongoid::Enum
enum :status, [:awaiting_approval, :approved, :banned]
end
expect(UserWithoutPrefix).to have_field "___status"
Mongoid::Enum.configure do |config|
config.field_name_prefix = old_field_name_prefix
end
end
it "is aliased" do
expect(instance).to respond_to alias_name
expect(instance).to respond_to :"#{alias_name}="
expect(instance).to respond_to :"#{alias_name}?"
expect(instance).to respond_to :"#{alias_name}"
end
describe "type" do
@ -50,14 +68,42 @@ describe Mongoid::Enum do
end
end
describe "'required' option" do
context "when true" do
let(:instance) { User.new status: nil }
it "is not valid with nil value" do
expect(instance).to_not be_valid
end
end
context "when false" do
let(:instance) { User.new roles: nil }
it "is valid with nil value" do
expect(instance).to be_valid
end
end
end
describe "constant" do
it "is set to the values" do
expect(klass::STATUS).to eq values
end
end
describe "accessors"do
describe "accessors" do
context "when singular" do
describe "setter" do
it "accepts strings" do
instance.status = 'banned'
expect(instance.status).to eq :banned
end
it "accepts symbols" do
instance.status = :banned
expect(instance.status).to eq :banned
end
end
describe "{{value}}!" do
it "sets the value" do
instance.save
@ -85,6 +131,33 @@ describe Mongoid::Enum do
end
context "when multiple" do
describe "setter" do
it "accepts strings" do
instance.roles = "author"
expect(instance.roles).to eq [:author]
end
it "accepts symbols" do
instance.roles = :author
expect(instance.roles).to eq [:author]
end
it "accepts arrays of strings" do
instance.roles = ['author', 'editor']
instance.save
puts instance.errors.full_messages
instance.reload
expect(instance.roles).to include(:author)
expect(instance.roles).to include(:editor)
end
it "accepts arrays of symbols" do
instance.roles = [:author, :editor]
expect(instance.roles).to include(:author)
expect(instance.roles).to include(:editor)
end
end
describe "{{value}}!" do
context "when field is nil" do
it "creates an array containing the value" do
@ -111,15 +184,15 @@ describe Mongoid::Enum do
instance.save
instance.author!
instance.editor!
expect(instance.editor?).to be_true
expect(instance.author?).to be_true
expect(instance.editor?).to be true
expect(instance.author?).to be true
end
end
context "when {{enum}} does not contain {{value}}" do
it "returns false" do
instance.save
expect(instance.author?).to be_false
expect(instance.author?).to be false
end
end
end
@ -174,4 +247,21 @@ describe Mongoid::Enum do
end
end
end
describe ".configuration" do
it "returns Configuration object" do
expect(Mongoid::Enum.configuration)
.to be_instance_of Mongoid::Enum::Configuration
end
it "returns same object when called multiple times" do
expect(Mongoid::Enum.configuration).to be Mongoid::Enum.configuration
end
end
describe ".configure" do
it "yields configuration if block is given" do
expect { |b| Mongoid::Enum.configure &b }
.to yield_with_args Mongoid::Enum.configuration
end
end
end

View File

@ -1,22 +1,18 @@
$: << File.expand_path("../../lib", __FILE__)
require 'database_cleaner'
require 'mongoid'
require 'mongoid-rspec'
require "mongoid/rspec"
require 'mongoid/enum'
ENV['MONGOID_ENV'] = "test"
RSpec.configure do |config|
config.include Mongoid::Matchers
config.before(:suite) do
DatabaseCleaner.strategy = :truncation
end
config.after(:each) do
DatabaseCleaner.clean
config.before(:each) do
Mongoid.purge!
end
end
Mongoid.load!(File.expand_path("../support/mongoid.yml", __FILE__), :test)
Mongo::Logger.logger.level = ::Logger::INFO

View File

@ -1,5 +1,5 @@
test:
sessions:
clients:
default:
database: mongoid-enum_test
hosts: