Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Created the attr_encodable plugin

  • Loading branch information...
commit 6bbb1a139d9bd804b62f69ff1fa338e2dc152bd7 0 parents
Flip Sasser authored
2  .gitignore
@@ -0,0 +1,2 @@
+coverage/*
+pkg/*
1  .rspec
@@ -0,0 +1 @@
+--colour
20 LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2011 Flip Sasser
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 README.md
@@ -0,0 +1,34 @@
+attr_encodable
+=
+
+**attr_encodable** adds attribute black- or white-listing for ActiveRecord serialization. It enables you to set up defaults for what is included or excluded when you serialize an ActiveRecord object. This is especially useful for protecting private attributes when building a public API.
+
+Install
+==
+
+Install using Rubygems:
+
+ gem install attr_encodable
+
+Install using Bundler:
+
+ gem 'attr_encodable'
+
+Install in Rails 2.x (in your environment.rb file)
+
+ config.gem 'attr_encodable'
+
+Usage
+==
+
+You can whitelist or blacklist attributes for serialization using the `attr_encodable` and `attr_unencodable` class methods. For example:
+
+class User < ActiveRecord::Base
+ attr_encodable :id, :name, :email
+end
+
+Now, when you call `to_json` on an instance of User, the only attributes that will be added to the JSON hash are :id, :name, and :email.
+
+`attr_unencodable` is similar, except that it bans an attribute.
+
+That's it. It's really, really, unbelievably simple. Enjoy!
62 Rakefile
@@ -0,0 +1,62 @@
+require 'rake'
+begin
+ require 'rspec/core'
+ require 'rspec/core/rake_task'
+rescue MissingSourceFile
+ module RSpec
+ module Core
+ class RakeTask
+ def initialize(name)
+ task name do
+ # if rspec-rails is a configured gem, this will output helpful material and exit ...
+ require File.expand_path(File.dirname(__FILE__) + "/../../config/environment")
+
+ # ... otherwise, do this:
+ raise <<-MSG
+
+#{"*" * 80}
+* You are trying to run an rspec rake task defined in
+* #{__FILE__},
+* but rspec can not be found. Try running 'gem install rspec'.
+#{"*" * 80}
+MSG
+ end
+ end
+ end
+ end
+ end
+end
+
+Rake.application.instance_variable_get('@tasks').delete('default')
+
+task :default => :spec
+
+desc "Run all specs in spec directory"
+RSpec::Core::RakeTask.new(:spec)
+
+namespace :spec do
+ desc "Run all specs with rcov"
+ RSpec::Core::RakeTask.new(:coverage) do |t|
+ t.pattern = 'spec/**/*_spec.rb'
+ t.rcov = true
+ t.rcov_opts = %w{--exclude osx\/objc,gems\/,spec\/,features\/}
+ t.verbose = true
+ end
+end
+
+require "jeweler"
+Jeweler::Tasks.new do |gemspec|
+ gemspec.name = "attr_encodable"
+ gemspec.summary = "An attribute black- or white-list for ActiveRecord serialization"
+ gemspec.files = Dir["{lib}/**/*", "LICENSE", "README.md"]
+ gemspec.description = %{
+ attr_encodable enables you to set up defaults for what is included or excluded when you serialize an ActiveRecord object. This is especially useful for protecting private attributes when building a public API.
+ }
+ gemspec.email = "flip@x451.com"
+ gemspec.homepage = "http://github.com/Plinq/attr_encodable"
+ gemspec.authors = ["Flip Sasser"]
+ gemspec.test_files = Dir["{spec}/**/*"]
+ gemspec.add_development_dependency 'rcov', '>= 0.9.9'
+ gemspec.add_development_dependency 'rspec', '>= 2.0'
+ gemspec.add_dependency 'redis', '>= 2.1.1'
+end
4 autotest/discover.rb
@@ -0,0 +1,4 @@
+require 'autotest/fsevent'
+require 'autotest/growl'
+
+Autotest.add_discovery { "rspec2" }
51 lib/attr_encodable.rb
@@ -0,0 +1,51 @@
+require 'active_record'
+
+module Encodable
+ module ClassMethods
+ def attr_encodable(*attributes)
+ unless @encodable_whitelist_started
+ unencodable_attributes.push *column_names.map(&:to_sym)
+ @encodable_whitelist_started = true
+ end
+ attributes.map!(&:to_sym)
+ unencodable_attributes.delete_if {|attribute| attributes.include? attribute }
+ end
+
+ def attr_unencodable(*attributes)
+ unencodable_attributes.push(*attributes.map(&:to_sym))
+ end
+
+ def unencodable_attributes
+ @unencodable_attributes ||= []
+ end
+ end
+
+ module InstanceMethods
+ def serializable_hash(options = {})
+ options ||= {}
+ unless self.class.unencodable_attributes.empty?
+ original_except = if options[:except]
+ options[:except] = Array(options[:except]).map(&:to_sym)
+ else
+ options[:except] = []
+ end
+ options[:except].push *self.class.unencodable_attributes
+ case options[:include]
+ when Array, Symbol
+ includes = Array(options[:include])
+ # This is a little bit confusing. ActiveRecord's default behavior is to apply the :except arguments you pass
+ # in to any :include options UNLESS it's overridden on the :include option. In the event that we have some
+ # *default* excepts that come from Encodable, we want to ignore those and pass only whatever the original
+ # :except options from the user were on down to the :include guys.
+ options[:include] = Hash[*includes.map{|association| [association, {:except => original_except - self.class.unencodable_attributes, :method => nil, :methods => []}]}.flatten]
+ end
+ end
+ super(options)
+ end
+ end
+end
+
+if defined? ActiveRecord::Base
+ ActiveRecord::Base.extend Encodable::ClassMethods
+ ActiveRecord::Base.send(:include, Encodable::InstanceMethods)
+end
144 spec/encodable_spec.rb
@@ -0,0 +1,144 @@
+require "lib/attr_encodable"
+
+describe Encodable do
+ it "should automatically extend ActiveRecord::Base" do
+ ActiveRecord::Base.should respond_to(:attr_encodable)
+ ActiveRecord::Base.should respond_to(:attr_unencodable)
+ end
+
+ before :each do
+ ActiveRecord::Base.include_root_in_json = false
+ ActiveRecord::Base.establish_connection({:adapter => 'sqlite3', :database => ':memory:', :pool => 5, :timeout => 5000})
+ class ::Permission < ActiveRecord::Base; belongs_to :user; def hello; "World!"; end; end
+ class ::User < ActiveRecord::Base; has_many :permissions; def foobar; "baz"; end; end
+ silence_stream(STDOUT) do
+ ActiveRecord::Schema.define do
+ create_table :permissions, :force => true do |t|
+ t.belongs_to :user
+ t.string :name
+ end
+ create_table :users, :force => true do |t|
+ t.string "login", :limit => 48
+ t.string "email", :limit => 128
+ t.string "first_name", :limit => 32
+ t.string "last_name", :limit => 32
+ t.string "encrypted_password", :limit => 60
+ t.boolean "developer", :default => false
+ t.boolean "admin", :default => false
+ t.boolean "password_set", :default => true
+ t.boolean "verified", :default => false
+ t.datetime "created_at"
+ t.datetime "updated_at"
+ t.integer "notifications"
+ end
+ end
+ end
+ @user = User.create({
+ :login => "flipsasser",
+ :first_name => "flip",
+ :last_name => "sasser",
+ :email => "flip@foobar.com",
+ :encrypted_password => ActiveSupport::SecureRandom.hex(30),
+ :developer => true,
+ :admin => true,
+ :password_set => true,
+ :verified => true,
+ :notifications => 7
+ })
+ @user.permissions.create(:name => "create_blog_posts")
+ @user.permissions.create(:name => "edit_blog_posts")
+ # Reset the options for each test
+ Permission.class_eval do
+ @encodable_whitelist_started = nil
+ @unencodable_attributes = nil
+ end
+ User.class_eval do
+ @encodable_whitelist_started = nil
+ @unencodable_attributes = nil
+ end
+ end
+
+ it "should favor whitelisting to blacklisting" do
+ User.unencodable_attributes.should == []
+ User.attr_unencodable 'foo', 'bar', 'baz'
+ User.unencodable_attributes.should == [:foo, :bar, :baz]
+ User.attr_encodable :id, :first_name
+ User.unencodable_attributes.map(&:to_s).should == ['foo', 'bar', 'baz'] + User.column_names - ['id', 'first_name']
+ end
+
+ describe "at the parent model level" do
+ it "should not mess with to_json unless when attr_encodable and attr_unencodable are not set" do
+ @user.as_json == @user.attributes
+ end
+
+ it "should not mess with :include options" do
+ @user.as_json(:include => :permissions) == @user.attributes.merge(:permissions => @user.permissions.as_json)
+ end
+
+ it "should not mess with :methods options" do
+ @user.as_json(:methods => :foobar) == @user.attributes.merge(:foobar => "baz")
+ end
+
+ it "should allow me to whitelist attributes" do
+ User.attr_encodable :login, :first_name, :last_name
+ @user.as_json.should == @user.attributes.slice('login', 'first_name', 'last_name')
+ end
+
+ it "should allow me to blacklist attributes" do
+ User.attr_unencodable :login, :first_name, :last_name
+ @user.as_json.should == @user.attributes.except('login', 'first_name', 'last_name')
+ end
+
+ # Of note is the INSANITY of ActiveRecord in that it applies :only / :except to :include as well. Which is
+ # obviously insane. Similarly, it doesn't allow :methods to come along when :only is specified. Good god, what
+ # a shame.
+ it "should allow me to whitelist attributes without messing with :include" do
+ User.attr_encodable :login, :first_name, :last_name
+ @user.as_json(:include => :permissions).should == @user.attributes.slice('login', 'first_name', 'last_name').merge(:permissions => @user.permissions.as_json)
+ end
+
+ it "should allow me to blacklist attributes without messing with :include and :methods" do
+ User.attr_unencodable :login, :first_name, :last_name
+ @user.as_json(:include => :permissions, :methods => :foobar).should == @user.attributes.except('login', 'first_name', 'last_name').merge(:permissions => @user.permissions.as_json, :foobar => "baz")
+ end
+
+ it "should not screw with :include if it's a hash" do
+ User.attr_unencodable :login, :first_name, :last_name
+ @user.as_json(:include => {:permissions => {:methods => :hello, :except => :id}}, :methods => :foobar).should == @user.attributes.except('login', 'first_name', 'last_name').merge(:permissions => @user.permissions.as_json(:methods => :hello, :except => :id), :foobar => "baz")
+ end
+ end
+
+ describe "at the child model level when the paren model has attr_encodable set" do
+ before :each do
+ User.attr_encodable :login, :first_name, :last_name
+ end
+
+ it "should not mess with to_json unless when attr_encodable and attr_unencodable are not set on the child, but are on the parent" do
+ @user.permissions.as_json == @user.permissions.map(&:attributes)
+ end
+
+ it "should not mess with :include options" do
+ # This is testing that the implicit ban on the :id attribute from User.attr_encodable is not
+ # applying to serialization of permissions
+ @user.as_json(:include => :permissions)[:permissions].first['id'].should_not be_nil
+ end
+
+ it "should inherit any attr_encodable options from the child model" do
+ User.attr_encodable :id
+ Permission.attr_encodable :name
+ as_json = @user.as_json(:include => :permissions)
+ as_json[:permissions].first['id'].should be_nil
+ as_json['id'].should_not be_nil
+ end
+
+ # it "should allow me to whitelist attributes" do
+ # User.attr_encodable :login, :first_name, :last_name
+ # @user.as_json.should == @user.attributes.slice('login', 'first_name', 'last_name')
+ # end
+ #
+ # it "should allow me to blacklist attributes" do
+ # User.attr_unencodable :login, :first_name, :last_name
+ # @user.as_json.should == @user.attributes.except('login', 'first_name', 'last_name')
+ # end
+ end
+end
Please sign in to comment.
Something went wrong with that request. Please try again.