Skip to content

Instantly share code, notes, and snippets.

@chriseppstein
Created September 3, 2008 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chriseppstein/8654 to your computer and use it in GitHub Desktop.
Save chriseppstein/8654 to your computer and use it in GitHub Desktop.
module Anonymizer
def anonymize_attribute(attribute)
self.send(:include, Module.new do
define_method attribute do
a = @attributes[attribute.to_s]
a && attribute.to_s.ends_with?("_id") ? a.to_i : a
end
define_method "#{attribute}_with_anonymous" do
send("#{attribute}_without_anonymous") unless anonymous?
end
end)
alias_method_chain attribute, :anonymous
end
def anonymize_method(method, options = {})
method_name, ending = split_method_name(method)
self.send(:include, Module.new do
if options[:superclass]
define_method method do |*arguments|
super(*arguments)
end
end
define_method "#{method_name}_with_anonymous#{ending}" do |*arguments|
send("#{method_name}_without_anonymous#{ending}", arguments) unless anonymous?
end
end)
alias_method_chain method, :anonymous
end
private
def split_method_name(method)
if ['?', '!'].include?(method.to_s.last)
[method.to_s[0..-2], method.to_s.last]
else
[method, nil]
end
end
end
# == Schema Information
#
# Table name: posts
#
# id :integer(11) not null, primary key
# user_id :integer(11)
# anonymous :boolean(1)
# ...
class Post < ActiveRecord::Base
extend Anonymizer
belongs_to :user
anonymize_method :user
anonymize_attribute :user_id
end
>> p = Post.find(:first, :conditions => {:anonymous => true})
=> #<Post id: 31, ... >
>> p.user
=> nil
>> p.user_id_with_anonymous
=> nil
>> p.user_id_without_anonymous
=> 1234
>> p.user_without_anonymous
=> #<User id: 1234, ... >
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment