Hides given attributes from serialization (to_xml, to_json, etc) by default.
MIT License
= AttrVisible
== Description
Makes it easy to list attributes that shouldn't be serialized by to_xml and friends.
First, use the writer +attr_visible+ to list attributes that shouldn't be shown to the world. Second, call +serialize_defaults+ with +:only => visible_attributes+. You may also list associations that you'd like to include, or any other argument accepted by {the ActiveRecord::Serialization methods}[http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html]
You can {only whitelist attributes}[http://bit.ly/default_permit_is_dumb].
== !! Please be aware !!
Nothing enforces these attributes to be hidden in general. You should use serialize_defaults to create a whitelist of attributes, and in your views you can use +visible_attributes+ to check whether fields are listed as visible.
== Example
class User has_many :roles has_many :posts # User has attributes name, email, password; and has_many roles.
# A user should to be able to modify her name and email, but not roles.
attr_accessible :name, :email, :password, :password_confirmation
# Let to_xml, to_json, etc show a user's id, name, roles and date they
# joined, but don't show their email or password visible to the world.
attr_visible :id, :name, :roles, :created_at
# Additionally show how many posts they've made
serialize_defaults :only => visible_attributes, :methods => :num_posts
# number of posts by this user
def num_posts
posts.count
end
end
Then we would get
user = User.new("name" => "David", "email" => "[email protected]", "password" => "monkey", ... ) user.to_json # {"user": { "id":1, "name":"David", "email":"[email protected]", :created_at => '...', :num_posts => 0 } }
Copyright (c) 2008 Philip (flip) Kromer for infochimps.org Released under the MIT license