Skip to content

Commit

Permalink
Merge pull request #4 from anthonator/feature/equals
Browse files Browse the repository at this point in the history
Overrode ==
  • Loading branch information
Anthony Smith committed Jan 22, 2017
2 parents 95afe26 + 2412352 commit 98b8e36
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 1 deletion.
4 changes: 4 additions & 0 deletions lib/soulless/model.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,5 +34,9 @@ def i18n_scope
def persisted?
false
end

def ==(o)
self.to_h == o.to_h
end
end
end
45 changes: 45 additions & 0 deletions lib/soulless/validations/using_validator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
module Soulless
module Validations
class UsingValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
check_options
return if should_not_continue?(value)

if value.is_a?(Array)
value.each { |v| perform(record, attribute, v) }
else
perform(record, attribute, value)
end
end

private

def check_options
fail(ArgumentError, 'The `:model` option is required for the `using` validator') unless options[:model]
fail(ArgumentError, 'The `:model` option should contain a class that responds to `valid?` for the `using` validator') unless options[:model].respond_to?(:new) && options[:model].method_defined?(:valid?)
end

def should_not_continue?(value)
(options[:allow_nil] && value.nil?) ||
(options[:allow_empty] && value.empty?)
end

def perform(record, attribute, value)
model = options[:model].new(value)

return if model.valid?

reference_value = model[options[:reference]] if options[:reference]

if !reference_value.blank?
errors = {}
errors[reference_value] = model.errors

record.errors[attribute] << errors
else
record.errors[attribute] << model.errors
end
end
end
end
end
2 changes: 1 addition & 1 deletion lib/soulless/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Soulless
VERSION = '1.1.1'
VERSION = '1.2.0'
end
7 changes: 7 additions & 0 deletions spec/soulless_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,11 @@

expect(model.changed?).to be_falsey
end

it 'should be equal if attributes are the same' do
model_1 = SoullessModel.new(email: 'anthony@sticksnleaves.com')
model_2 = SoullessModel.new(email: 'anthony@sticksnleaves.com')

expect(model_1).to eq model_2
end
end

0 comments on commit 98b8e36

Please sign in to comment.