Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
dce committed Jul 9, 2009
0 parents commit 9f0b5af
Show file tree
Hide file tree
Showing 9 changed files with 273 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -0,0 +1 @@
test.db
20 changes: 20 additions & 0 deletions MIT-LICENSE
@@ -0,0 +1,20 @@
Copyright (c) 2009 [name of plugin creator]

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.
13 changes: 13 additions & 0 deletions README
@@ -0,0 +1,13 @@
SerializeWithOptions
====================

Introduction goes here.


Example
=======

Example goes here.


Copyright (c) 2009 [name of plugin creator], released under the MIT license
23 changes: 23 additions & 0 deletions Rakefile
@@ -0,0 +1,23 @@
require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'

desc 'Default: run unit tests.'
task :default => :test

desc 'Test the serialize_with_options plugin.'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
t.verbose = true
end

desc 'Generate documentation for the serialize_with_options plugin.'
Rake::RDocTask.new(:rdoc) do |rdoc|
rdoc.rdoc_dir = 'rdoc'
rdoc.title = 'SerializeWithOptions'
rdoc.options << '--line-numbers' << '--inline-source'
rdoc.rdoc_files.include('README')
rdoc.rdoc_files.include('lib/**/*.rb')
end
1 change: 1 addition & 0 deletions init.rb
@@ -0,0 +1 @@
ActiveRecord::Base.extend(SerializeWithOptions)
61 changes: 61 additions & 0 deletions lib/serialize_with_options.rb
@@ -0,0 +1,61 @@
module SerializeWithOptions
def serialize_with_options(&block)
config = Config.new
config.instance_eval(&block)

write_inheritable_attribute(:serialization_options, config.options)

extend ClassMethods
include InstanceMethods
end

def serialization_options
read_inheritable_attribute(:serialization_options) || {}
end

class Config
attr_accessor :options

def initialize
@options = {}
end

def methods(*args)
@options[:methods] = args
end

def includes(*args)
@options[:include] = args
end

def except(*args)
@options[:except] = args
end
end

module ClassMethods
def configure_includes
opts = serialization_options

if opts[:include].is_a? Array
opts[:include] = opts[:include].inject({}) do |hash, class_name|
klass = class_name.to_s.singularize.capitalize.constantize
hash[class_name] = klass.serialization_options.dup.merge(:include => nil)
hash
end
end
end
end

module InstanceMethods
def to_xml(opts = {})
self.class.configure_includes
super(self.class.serialization_options.merge(opts))
end

def to_json(opts = {})
self.class.configure_includes
super(self.class.serialization_options.merge(opts))
end
end
end
4 changes: 4 additions & 0 deletions tasks/serialize_with_options_tasks.rake
@@ -0,0 +1,4 @@
# desc "Explaining what the task does"
# task :serialize_with_options do
# # Task goes here
# end
89 changes: 89 additions & 0 deletions test/serialize_with_options_test.rb
@@ -0,0 +1,89 @@
require 'test_helper'

class SerializeWithOptionsTest < Test::Unit::TestCase
context "An instance of a class with serialization options" do
setup do
@user = User.create(:name => "John User", :email => "john@example.com")
@post = @user.posts.create(:title => "Hello World!", :content => "Welcome to my blog.")
@comment = @post.comments.create(:content => "Great blog!")
end

context "being converted to XML" do
setup do
@user_xml = Hash.from_xml(@user.to_xml)["user"]
@post_xml = Hash.from_xml(@post.to_xml)["post"]
end

should "include active_record attributes" do
assert_equal @user.name, @user_xml["name"]
end

should "include specified methods" do
assert_equal @user.post_count, @user_xml["post_count"]
end

should "exclude specified attributes" do
assert_equal nil, @user_xml["email"]
end

should "include specified associations" do
assert_equal @post.title, @user_xml["posts"].first["title"]
end

should "include specified methods on associations" do
assert_equal @user.post_count, @post_xml["user"]["post_count"]
end

should "exclude specified methods on associations" do
assert_equal nil, @post_xml["user"]["email"]
end

should "not include associations of associations" do
assert_equal nil, @user_xml["posts"].first["comments"]
end

should "include association without serialization options properly" do
assert_equal @comment.content, @post_xml["comments"].first["content"]
end
end

context "being converted to JSON" do
setup do
@user_json = JSON.parse(@user.to_json)
@post_json = JSON.parse(@post.to_json)
end

should "include active_record attributes" do
assert_equal @user.name, @user_json["name"]
end

should "include specified methods" do
assert_equal @user.post_count, @user_json["post_count"]
end

should "exclude specified attributes" do
assert_equal nil, @user_json["email"]
end

should "include specified associations" do
assert_equal @post.title, @user_json["posts"].first["title"]
end

should "include specified methods on associations" do
assert_equal @user.post_count, @post_json["user"]["post_count"]
end

should "exclude specified methods on associations" do
assert_equal nil, @post_json["user"]["email"]
end

should "not include associations of associations" do
assert_equal nil, @user_json["posts"].first["comments"]
end

should "include association without serialization options properly" do
assert_equal @comment.content, @post_json["comments"].first["content"]
end
end
end
end
61 changes: 61 additions & 0 deletions test/test_helper.rb
@@ -0,0 +1,61 @@
require 'rubygems'
require 'active_record'
require 'test/unit'
require 'shoulda'
require 'json'

$:.unshift(File.dirname(__FILE__) + '/../lib')
require 'serialize_with_options'
require File.dirname(__FILE__) + "/../init"

ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:dbfile => 'test.db'
)

ActiveRecord::Base.connection.drop_table :users rescue nil
ActiveRecord::Base.connection.drop_table :posts rescue nil
ActiveRecord::Base.connection.drop_table :comments rescue nil

ActiveRecord::Base.connection.create_table :users do |t|
t.string :name
t.string :email
end

ActiveRecord::Base.connection.create_table :posts do |t|
t.string :title
t.text :content
t.integer :user_id
end

ActiveRecord::Base.connection.create_table :comments do |t|
t.text :content
t.integer :post_id
end

class User < ActiveRecord::Base
has_many :posts

serialize_with_options do
methods :post_count
includes :posts
except :email
end

def post_count
self.posts.count
end
end

class Post < ActiveRecord::Base
has_many :comments
belongs_to :user

serialize_with_options do
includes :user, :comments
end
end

class Comment < ActiveRecord::Base
belongs_to :post
end

0 comments on commit 9f0b5af

Please sign in to comment.