Skip to content

Instantly share code, notes, and snippets.

@dasibre
Forked from fnando/polite.rb
Last active September 14, 2015 23:11
Show Gist options
  • Save dasibre/e148f657169bcc19b760 to your computer and use it in GitHub Desktop.
Save dasibre/e148f657169bcc19b760 to your computer and use it in GitHub Desktop.
ActiveRecord macro example
require "active_record"
module Polite
BAD_WORDS = ["fuck", "asshole", "motherfucker", "cunt", "cock", "dickhead"]
ESCAPED = BAD_WORDS.collect {|word| Regexp.escape(word)}
RE = /(#{ESCAPED.join("|")})/i
def self.extended(base)
base.extend ClassMethods
end
end
module Polite
module ClassMethods
def be_polite(*names)
before_save :remove_bad_words_from_attributes
cattr_accessor :polite_attributes
self.polite_attributes = names
include InstanceMethods
end
end
end
module Polite
module InstanceMethods
private
def remove_bad_words_from_attributes
self.class.polite_attributes.each do |attribute|
remove_bad_words_from(attribute)
end
end
def remove_bad_words_from(attribute)
value = send(attribute).to_s.gsub(RE) { $1[0,1] << "*" }
send("#{attribute}=", value)
end
end
end
# Extend ActiveRecord
ActiveRecord::Base.extend(Polite)
# Establish connection
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
# Create a demo table
ActiveRecord::Schema.define(:version => 0) do
create_table :comments do |t|
t.text :body
end
end
# Create a demo model
class Comment < ActiveRecord::Base
be_polite :body
end
comment = Comment.create(:body => "Fuck you, asshole!")
p comment.body
#=> "F* you, a*!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment