Module: AttrSanitizable::ClassMethods

Defined in:
lib/attr_sanitizable.rb

Instance Method Summary collapse

Instance Method Details

#attr_sanitizable(*attributes) ⇒ Object

Raises:

  • (ArgumentError)


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/attr_sanitizable.rb', line 11

def attr_sanitizable(*attributes)
  raise ArgumentError, "You need to supply at least one attribute" if attributes.empty?

  defaults = attributes.extract_options!.dup
  actions  = defaults[:with] || []

  attributes.each do |field|
    define_method "#{field}=" do |value|
      return if value.nil?
      
      actions.compact.each do |action|
        raise ArgumentError, "Unable to perform '#{action}' on a variable of type '#{value.class.name}'" unless value.respond_to?([*action].first)
        value = value.send(*[*action])
      end

      write_attribute(field, value)
    end
  end
end