module AttrSanitizable::ClassMethods

Public Instance Methods

attr_sanitizable(*attributes) click to toggle source
# 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