Class: Completeness::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/completeness/field.rb

Constant Summary collapse

DEFAULT_WEIGHT =
10

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(spec, name, options = {}) ⇒ Field

Returns a new instance of Field.



7
8
9
10
11
# File 'lib/completeness/field.rb', line 7

def initialize(spec, name, options = {})
  @spec = spec
  @name = name
  @options = options
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/completeness/field.rb', line 5

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/completeness/field.rb', line 5

def options
  @options
end

#specObject (readonly)

Returns the value of attribute spec.



5
6
7
# File 'lib/completeness/field.rb', line 5

def spec
  @spec
end

Instance Method Details

#<=>(other) ⇒ Object



25
26
27
28
29
# File 'lib/completeness/field.rb', line 25

def <=>(other)
  return 1 if required? && !other.required?
  return -1 if !required? && other.required?
  weight <=> other.weight
end

#completed?(object) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
# File 'lib/completeness/field.rb', line 17

def completed?(object)
  completeness_check.call(object, object.send(name))
end

#completeness_checkObject



35
36
37
38
39
40
41
# File 'lib/completeness/field.rb', line 35

def completeness_check
  if options[:check].present? && options[:check].respond_to?(:call)
    options[:check]
  else
    ->(obj, value){ value.present? }
  end
end

#required?Boolean

Returns:

  • (Boolean)


13
14
15
# File 'lib/completeness/field.rb', line 13

def required?
  !!options[:required]
end

#weightObject



21
22
23
# File 'lib/completeness/field.rb', line 21

def weight
  options[:weight] || DEFAULT_WEIGHT
end

#weight_in_percentObject



31
32
33
# File 'lib/completeness/field.rb', line 31

def weight_in_percent
  (weight / (spec.total_weight / 100.0)).round
end