Module: Checkboxes::Core

Extended by:
Core
Included in:
Core
Defined in:
lib/checkboxes/core.rb

Overview

This module contains utility methods for both extensions and helpers.

Defined Under Namespace

Classes: CheckboxesNameError

Instance Method Summary collapse

Instance Method Details

#field_name(relation) ⇒ String

Returns a pattern name for the attr_accessor used for handling checkboxes.

Returns:

  • (String)


41
42
43
# File 'lib/checkboxes/core.rb', line 41

def field_name(relation)
  "__#{relation}_ids"
end

#relation_klass(klass, relation) ⇒ class

Returns the class of a relation of of a given class. It cares about the source option of the has_many.

Returns:

  • (class)


33
34
35
36
37
# File 'lib/checkboxes/core.rb', line 33

def relation_klass(klass, relation)
  source=klass.reflections[relation].options[:source]
  relation_klass = source.present? ? source.to_s : relation.to_s
  relation_klass.classify.constantize
end

#validate(klass, *relations) ⇒ boolean

TODO:

makes error raised more specific

Checks the validity of the relations on a given class. A relation will be valid:

  • It exists

  • It’s an _has_many

  • It uses the through option

Returns:

  • (boolean)

    It returns true, it raises an exception if the validation fails.

Raises:

  • CheckboxesNameError Generic Error



18
19
20
21
22
23
24
25
26
# File 'lib/checkboxes/core.rb', line 18

def validate(klass, *relations)
  for relation in relations
    unless (klass.reflections[relation].present? &&
            klass.reflections[relation].macro == :has_many &&
            klass.reflections[relation].options[:through].present?)
      raise CheckboxesNameError, "#{relation} isn't an has_many :through for model #{klass}, check it out please."
    end
  end
end