Module: DespamilatorRails
- Defined in:
- lib/despamilator_rails.rb,
lib/despamilator_rails/data_mapper_validator.rb,
lib/despamilator_rails/active_record_validator.rb
Defined Under Namespace
Modules: ActiveRecordValidator, DataMapperValidator
Instance Method Summary collapse
-
#validate_with_despamilator(settings, &block) ⇒ Object
In your model (basic example):.
Instance Method Details
#validate_with_despamilator(settings, &block) ⇒ Object
In your model (basic example):
class YourModel < ActiveRecord::Base
validate_with_despamilator :attributes => [:some_field]
end
When “some_field” is assigned a spammy value, it will add to the errors. For example…
YourModel.new(:some_field => spammy_value).save! #=> ActiveRecord::RecordInvalid exception!
Or…
your_instance = YourModel.new(:some_field => spammy_value)
your_instance.save
your_instance.errors..should #=> ["Some field looks like spam"]
Note that, by default, DataMapper behaves slightly differently in that it will not raise exceptions unless you code a callback to deal with that. Instead it will return “false” on an unsuccessful save.
If you want to configure the threshold (which defaults to 1) or add your own callback, you can do the following:
class YourModel < ActiveRecord::Base
validate_with_despamilator :attributes => [:some_field], :threshold => 1 do |field, value, despamilator|
raise "spam! field: #{field}, value: #{value}, score: #{despamailtor.score}"
end
end
This example will…
your_instance = YourModel.new(:some_field => "spammy string")
your_instance.save! #=> Exception "spam! field: some_field, value: spammy string, score: 123"
The callback will receive the field name, the value and the instance of the Despamilator class.
51 52 53 54 55 56 57 58 |
# File 'lib/despamilator_rails.rb', line 51 def validate_with_despamilator settings, & block extend(respond_to?(:validates_with_block) ? DespamilatorRails::DataMapperValidator : DespamilatorRails::ActiveRecordValidator) assign_despamilator_threshold settings assign_despamilator_callback block add_despamilator_validation settings end |