Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

source 'https://rubygems.org'

# Specify your gem's dependencies in mongoid-enum.gemspec
Expand Down
4 changes: 2 additions & 2 deletions Guardfile
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# A sample Guardfile
# More info at https://github.com/guard/guard#readme

guard :rspec, cmd: "bundle exec rspec" do
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" }
watch('spec/spec_helper.rb') { 'spec' }
end
4 changes: 3 additions & 1 deletion Rakefile
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
require "bundler/gem_tasks"
# frozen_string_literal: true

require 'bundler/gem_tasks'
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Style/StringLiterals: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

48 changes: 27 additions & 21 deletions lib/mongoid/enum.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
require "mongoid/enum/version"
require "mongoid/enum/validators/multiple_validator"
require "mongoid/enum/configuration"
# frozen_string_literal: true

require 'mongoid/enum/version'
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Style/StringLiterals: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

require 'mongoid/enum/validators/multiple_validator'
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Style/StringLiterals: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

require 'mongoid/enum/configuration'
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Style/StringLiterals: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.


module Mongoid
module Enum
extend ActiveSupport::Concern
module ClassMethods

def enum(name, values, options = {})
field_name = :"#{Mongoid::Enum.configuration.field_name_prefix}#{name}"
options = default_options(values).merge(options)
Expand All @@ -21,12 +22,13 @@ def enum(name, values, options = {})
end

private

def default_options(values)
{
:multiple => false,
:default => values.first,
:required => true,
:validate => true
multiple: false,
default: values.first,
required: true,
validate: true
}
end

Expand All @@ -37,21 +39,22 @@ def set_values_constant(name, values)

def create_field(field_name, options)
type = options[:multiple] && Array || Symbol
field field_name, :type => type, :default => options[:default]
field field_name, type: type, default: options[:default]
end

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]` ???
validates field_name,
'mongoid/enum/validators/multiple': { in: values.map(&:to_sym), allow_nil: !options[:required] }
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [116/80]

# FIXME: Shouldn't this be `elsif options[:validate]` ???
elsif validate
validates field_name, :inclusion => {:in => values.map(&:to_sym)}, :allow_nil => !options[:required]
validates field_name, inclusion: { in: values.map(&:to_sym) }, allow_nil: !options[:required]
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [103/80]

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 options[:multiple]
define_array_accessor(field_name, value)
Expand All @@ -70,23 +73,26 @@ def define_field_accessor(name, field_name, options)
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"
class_eval "def #{name}=(vals) self.write_attribute(:#{field_name}, Array(vals).compact.map(&:to_sym)) end",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [116/80]

__FILE__, __LINE__ - 1
class_eval "def #{name}() self.read_attribute(:#{field_name}) end", __FILE__, __LINE__
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [94/80]

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"
class_eval "def #{name}=(val) self.write_attribute(:#{field_name}, val && val.to_sym || nil) end", __FILE__,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [116/80]

__LINE__ - 1
class_eval "def #{name}() self.read_attribute(:#{field_name}) end", __FILE__, __LINE__
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [94/80]

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"
class_eval "def #{value}?() self.#{field_name}.include?(:#{value}) end", __FILE__, __LINE__
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [99/80]

class_eval "def #{value}!() update_attributes! :#{field_name} => (self.#{field_name} || []) + [:#{value}] end",
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [119/80]

__FILE__, __LINE__ - 1
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"
class_eval "def #{value}?() self.#{field_name} == :#{value} end", __FILE__, __LINE__
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [92/80]

class_eval "def #{value}!() update_attributes! :#{field_name} => :#{value} end", __FILE__, __LINE__
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [107/80]

end
end
end
Expand Down
4 changes: 3 additions & 1 deletion lib/mongoid/enum/configuration.rb
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
# frozen_string_literal: true

module Mongoid
module Enum
class Configuration
attr_accessor :field_name_prefix

def initialize
self.field_name_prefix = "_"
self.field_name_prefix = '_'
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Style/StringLiterals: Prefer double-quoted strings unless you need single quotes to avoid extra backslashes for escaping.

end
end

Expand Down
10 changes: 6 additions & 4 deletions lib/mongoid/enum/validators/multiple_validator.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# frozen_string_literal: true

module Mongoid
module Enum
module Validators
Expand All @@ -6,14 +8,14 @@ def validate_each(record, attribute, values)
values = Array(values)

if options[:allow_nil]
add_error_message record, attribute if !all_included?(values, options[:in])
else
add_error_message record, attribute if values.empty? || !all_included?(values, options[:in])
add_error_message record, attribute unless all_included?(values, options[:in])
elsif values.empty? || !all_included?(values, options[:in])
add_error_message record, attribute
end
end

def add_error_message(record, attribute)
record.errors[attribute] << (options[:message] || "is not in #{options[:in].join ", "}")
record.errors[attribute] << (options[:message] || "is not in #{options[:in].join ', '}")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Metrics/LineLength: Line is too long. [98/80]

end

def all_included?(values, allowed)
Expand Down
4 changes: 3 additions & 1 deletion lib/mongoid/enum/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

module Mongoid
module Enum
VERSION = "0.4.0"
VERSION = '0.4.0'
end
end
33 changes: 17 additions & 16 deletions mongoid-enum.gemspec
Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
# frozen_string_literal: true

lib = File.expand_path('lib', __dir__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'mongoid/enum/version'

Gem::Specification.new do |spec|
spec.name = "mongoid-enum"
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.summary = %q{Sweet enum sugar for your Mongoid documents}
spec.homepage = "https://github.com/thetron/mongoid-enum"
spec.license = "MIT"
spec.authors = ['Nicholas Bruning']
spec.email = ['nicholas@bruning.com.au']
spec.description = "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.summary = 'Sweet enum sugar for your Mongoid documents'
spec.homepage = 'https://github.com/thetron/mongoid-enum'
spec.license = 'MIT'

spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.require_paths = ['lib']

spec.add_runtime_dependency "mongoid", "~> 5.0"
spec.add_runtime_dependency 'mongoid', '>= 5.0', '<= 8.0'

spec.add_development_dependency "bundler", "~> 1.3"
spec.add_development_dependency "rake"
spec.add_development_dependency "rspec", "~> 3.1"
spec.add_development_dependency "guard-rspec", "~> 4.6.2"
spec.add_development_dependency "mongoid-rspec", "~> 3.0"
spec.add_development_dependency 'bundler', '~> 2.0'
spec.add_development_dependency 'guard-rspec', '~> 4.6.2'
spec.add_development_dependency 'mongoid-rspec', '~> 4.0'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec', '~> 3.1'
end
6 changes: 4 additions & 2 deletions spec/mongoid/configuration_spec.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
# frozen_string_literal: true

require 'spec_helper'

describe Mongoid::Enum::Configuration do
subject { Mongoid::Enum::Configuration.new }

describe "field_name_prefix" do
describe 'field_name_prefix' do
it "has '_' as default value" do
expect(subject.field_name_prefix).to eq "_"
expect(subject.field_name_prefix).to eq '_'
end
end
end
42 changes: 22 additions & 20 deletions spec/mongoid/enum/validators/multiple_validator_spec.rb
Original file line number Diff line number Diff line change
@@ -1,75 +1,77 @@
# frozen_string_literal: true

require 'spec_helper'
require 'ostruct'

describe Mongoid::Enum::Validators::MultipleValidator do
subject { Mongoid::Enum::Validators::MultipleValidator }
let(:values) { [:lorem, :ipsum, :dolor, :sit] }
let(:values) { %i[lorem ipsum dolor sit] }
let(:attribute) { :word }
let(:record) { OpenStruct.new(:errors => {attribute => []}, attribute => values.first) }
let(:record) { OpenStruct.new(:errors => { attribute => [] }, attribute => values.first) }
let(:allow_nil) { false }
let(:validator) { subject.new(:attributes => attribute, :in => values, :allow_nil => allow_nil) }
let(:validator) { subject.new(attributes: attribute, in: values, allow_nil: allow_nil) }

describe ".validate_each" do
context "when allow_nil: true" do
describe '.validate_each' do
context 'when allow_nil: true' do
let(:allow_nil) { true }

context "and value is nil" do
context 'and value is nil' do
before(:each) { validator.validate_each(record, attribute, nil) }
it "validates" do
it 'validates' do
expect(record.errors[attribute].empty?).to be true
end
end

context "and value is []" do
context 'and value is []' do
before(:each) { validator.validate_each(record, attribute, []) }
it "validates" do
it 'validates' do
expect(record.errors[attribute].empty?).to be true
end
end
end

context "when allow_nil: false" do
context "and value is nil" do
context 'when allow_nil: false' 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]).to eq ["is not in #{values.join ", "}"]
expect(record.errors[attribute]).to eq ["is not in #{values.join ', '}"]
end
end
context "and value is []" do
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]).to eq ["is not in #{values.join ", "}"]
expect(record.errors[attribute]).to eq ["is not in #{values.join ', '}"]
end
end
end

context "when value is included" do
context 'when value is included' do
let(:allow_nil) { rand(2).zero? }
before(:each) { validator.validate_each(record, attribute, [values.sample]) }
it "validates" do
it 'validates' do
expect(record.errors[attribute].empty?).to be true
end
end

context "when value is not included" do
context 'when value is not included' 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
end
end

context "when multiple values included" do
context 'when multiple values included' do
let(:allow_nil) { rand(2).zero? }
before(:each) { validator.validate_each(record, attribute, [values.first, values.last]) }
it "validates" do
it 'validates' do
expect(record.errors[attribute].empty?).to be true
end
end

context "when one value is not included "do
context 'when one value is not included ' do
let(:allow_nil) { rand(2).zero? }
before(:each) { validator.validate_each(record, attribute, [values.first, values.last, :amet]) }
it "won't validate" do
Expand Down
Loading