Module: Scrubby::ClassMethods

Defined in:
lib/scrubby.rb

Instance Method Summary collapse

Instance Method Details

#scrub(*attributes, &block) ⇒ Object

scrub accepts multiple symbol or string arguments, representing model attributes that are to be scrubbed before being set. The scrub method accepts no options, but an optional block can be included which will be used for scrubbing. Otherwise, the scrub instance method is used.

The scrub instance method and the optional block both expect one argument: the incoming attribute value, and should return one value: the new, all-cleaned-up attribute value. However, when a custom block is given, the single argument can be left out if for some reason it’s not needed.

Examples

class User < ActiveRecord::Base
  scrub :first_name, :last_name
end

class User < ActiveRecord::Base
  scrub :first_name, :last_name do |value|
    value.blank? ? nil : value.titleize
  end
end

class User < ActiveRecord::Base
  scrub(:first_name){|v| v.to_s.upcase }
  scrub(:last_name){ nil }
end


63
64
65
66
# File 'lib/scrubby.rb', line 63

def scrub(*attributes, &block)
  scrubber = block_given? ? block : instance_method(:scrub)
  self.scrubbers = attributes.inject({}){|s,a| s.merge!(a.to_s => scrubber) }
end

#scrubby?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/scrubby.rb', line 68

def scrubby?
  !scrubbers.blank?
end