Module: ThroughCheckboxes::Core

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

Overview

This module contains utility methods for both extensions and helpers.

Defined Under Namespace

Classes: ThroughCheckboxesNameError

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)


39
40
41
# File 'lib/throughcheckboxes/core.rb', line 39

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)


31
32
33
34
35
# File 'lib/throughcheckboxes/core.rb', line 31

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:

  • ThroughCheckboxesNameError Generic Error



16
17
18
19
20
21
22
23
24
# File 'lib/throughcheckboxes/core.rb', line 16

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 ThroughCheckboxesNameError, "#{relation} isn't an has_many :through for model #{klass}, check it out please."
        end
    end
end