Module: MongoUtils::Stripable

Defined in:
lib/mongo_utils/stripable.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/mongo_utils/stripable.rb', line 22

def self.included(base)
  base.send :include, Mongoid::Document

  base.around_create do |&b|
    attributes.reject! { |_, value| blank_value?(value) }
    b.call
    apply_defaults
  end

  base.around_update do |&b|
    attributes.reject! { |a, v|
      blank_and_was_blank_value?(a, v)
    }
    b.call
    apply_defaults
  end
end

Instance Method Details

#blank_and_was_blank_value?(attribute, value) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/mongo_utils/stripable.rb', line 18

def blank_and_was_blank_value?(attribute, value)
  plain_value_blank?(value) && respond_to?("#{attribute}_was") && blank_value?(send("#{attribute}_was"))
end

#blank_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


3
4
5
6
7
8
# File 'lib/mongo_utils/stripable.rb', line 3

def blank_value?(value)
  if value.is_a?(Hash)
    value.reject! { |_, v| blank_value?(v) }
  end
  plain_value_blank?(value)
end

#plain_value_blank?(value) ⇒ Boolean

Returns:

  • (Boolean)


10
11
12
13
14
15
16
# File 'lib/mongo_utils/stripable.rb', line 10

def plain_value_blank?(value)
  if value.is_a?(Hash)
    value = value.dup
    value.reject! { |_, v| plain_value_blank?(v) }
  end
  value.blank? || value == 0
end