Module: Inquisition::ClassMethods

Defined in:
lib/inquisition.rb

Instance Method Summary collapse

Instance Method Details

#sanitize_attribute(*attributes) ⇒ Object



22
23
24
25
# File 'lib/inquisition.rb', line 22

def sanitize_attribute(*attributes)
  sanitize_attribute_reader(*attributes)
  sanitize_attribute_writer(*attributes)
end

#sanitize_attribute_reader(*attributes) ⇒ Object



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

def sanitize_attribute_reader(*attributes)
  options = attributes.last.is_a?(::Hash) ? attributes.pop : {}
  if respond_to?(:cleansed_attr_readers)
    write_inheritable_attribute(:cleansed_attr_readers, cleansed_attr_readers.concat(attributes))
    write_inheritable_attribute(:cleansed_attr_reader_options, cleansed_attr_reader_options.merge(options))
  else
    write_inheritable_attribute(:cleansed_attr_readers, attributes)
    write_inheritable_attribute(:cleansed_attr_reader_options, options)
    class_inheritable_reader(:cleansed_attr_readers)
    class_inheritable_reader(:cleansed_attr_reader_options)

    define_method(:read_attribute_with_cleansing) do |attribute|
      value = read_attribute_without_cleansing(attribute)
      if cleansed_attr_readers.include?(attribute.to_sym) && !value.blank?
        Inquisition.sanitize(value,
          cleansed_attr_reader_options[:allow] ? cleansed_attr_reader_options[:allow][attribute.to_sym] : nil)
      else
        value
      end
    end
    alias_method_chain :read_attribute, :cleansing
  end

  attributes.each { |attr| define_method(attr.to_sym) { read_attribute(attr.to_sym) } }
end

#sanitize_attribute_writer(*attributes) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/inquisition.rb', line 53

def sanitize_attribute_writer(*attributes)
  options = attributes.last.is_a?(::Hash) ? attributes.pop : {}
  if respond_to?(:cleansed_attr_writers)
    write_inheritable_attribute(:cleansed_attr_writers, cleansed_attr_writers.concat(attributes))
    write_inheritable_attribute(:cleansed_attr_writer_options, cleansed_attr_writer_options.merge(options))
  else
    write_inheritable_attribute(:cleansed_attr_writers, attributes)
    write_inheritable_attribute(:cleansed_attr_writer_options, options)
    class_inheritable_reader(:cleansed_attr_writers)
    class_inheritable_reader(:cleansed_attr_writer_options)

    define_method(:write_attribute_with_cleansing) do |attribute, value|
      if cleansed_attr_writers.include?(attribute.to_sym) && !value.blank?
        Inquisition.sanitize(value,
          cleansed_attr_writer_options[:allow] ? cleansed_attr_writer_options[:allow][attribute.to_sym] : nil)
      end
      write_attribute_without_cleansing(attribute, value)
    end
    alias_method_chain :write_attribute, :cleansing
  end
end