Module: JcheckRails

Extended by:
JcheckRails
Included in:
JcheckRails
Defined in:
lib/jcheck_rails.rb,
lib/jcheck_rails/encoder.rb

Defined Under Namespace

Modules: Encoder Classes: Engine

Instance Method Summary collapse

Instance Method Details

#jcheck_for(object, attribute = nil, options = {}) ⇒ Object

This will reflect into your model and generate correct jCheck validations for you. In first argument you should send the current object of model, if you want to get just the validations for an given attribute, send the attribute name as second parameter. In third parameter you can send options to be used in jCheck initialization, but there some special keys that can be sent in the options.

<%= form_for(@object) do |f| %>
  ...
<% end %>
<%= jcheck_for(@object) %>

Configuration options:

  • :variable - Variable name to be used in javascript (default is: “validator”)

  • :form_id - The id of form in html to be used in jQuery selector (default is same behaviour as form_for do to generate form id)

  • :field_prefix - Field prefix to be used into jCheck, send nil to avoid field_prefix (default is same prefix as form_for will do)

Also, any other configuration option will be sent to jCheck() initializer.



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/jcheck_rails.rb', line 31

def jcheck_for(object, attribute = nil, options = {})
  return jcheck_for_object_attribute(object, attribute) if attribute
  
  options.reverse_merge!(
    :variable => "validator",
    :form_id => ActionController::RecordIdentifier.dom_id(object, (object.respond_to?(:persisted?) && object.persisted? ? :edit : nil)),
    :field_prefix => ActiveModel::Naming.singular(object)
  )
  
  variable = options.delete :variable
  form_id = options.delete :form_id
  
  validations = []
  
  object.class._validators.each do |attribute, validators|
    attr_validations = jcheck_for_object_attribute(object, attribute)
    
    validations << "#{variable}.validates(#{Encoder.convert_to_javascript attribute}, #{attr_validations});"
  end
  
  %{<script type="text/javascript"> jQuery(function() { var #{variable} = jQuery('##{form_id}').jcheck(#{Encoder.convert_to_javascript(options)}); #{validations.join(" ")} }); </script>}.html_safe
end

#jcheck_for_object_attribute(object, attribute) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/jcheck_rails.rb', line 54

def jcheck_for_object_attribute(object, attribute)
  validations = object.class._validators[attribute].inject([]) do |acc, validator|
    options = filter_validator_options(validator)
    
    acc << "#{Encoder.convert_to_javascript validator.kind}: #{Encoder.convert_to_javascript(options)}"
  end
  
  "{#{validations.join(', ')}}"
end