Module: ActionView::Helpers::FormHelper

Defined in:
lib/need_label/helpers.rb

Instance Method Summary collapse

Instance Method Details

#need_label(object_name, object, method, content_or_options = nil, options = nil, &block) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/need_label/helpers.rb', line 6

def need_label(object_name, object, method, content_or_options = nil, options = nil, &block)
  need = true
  if content_or_options.class == Hash && content_or_options[:need_label] == false
    need = false
    content_or_options.delete(:need_label)
    content_or_options = nil if content_or_options == {}
  end
  need = false if options.class == Hash && options[:need_label] == false
  if need && object.present? && object.class.respond_to?(:validators)
    need_attributes = []
    object.class.validators.each do |validator|
      if validator.is_a? ActiveModel::Validations::PresenceValidator
        if validator.options[:if].nil?
          need_attributes << validator
        else
          if validator.options[:if].is_a? Proc
            need_attributes << validator if object.instance_eval(&validator.options[:if])
          elsif validator.options[:if].is_a? String
            need_attributes << validator if object.instance_eval(&eval("proc{#{validator.options[:if]}}"))
          end
        end
      end
    end
    need_attributes.map!{|e| e.attributes[0]}
    if need_attributes.index(method.to_sym)
      if content_or_options.present? && content_or_options.class == Hash && content_or_options[:class].present?
        content_or_options[:class] = content_or_options[:class] + ' need-label'
      else
        options[:class] = 'need-label'
      end
    end
  end
  label(object_name, method, content_or_options, options, &block)
end