json_serializer 0.0.1 → 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
data/README.md
CHANGED
@@ -18,7 +18,86 @@ Or install it yourself as:
|
|
18
18
|
|
19
19
|
## Usage
|
20
20
|
|
21
|
-
|
21
|
+
The gem offers two primary features, serialize ActiveRecord models and collections into JSON and providing JSON Output helpers for an API.
|
22
|
+
|
23
|
+
### ActiveRecord Patch and Custom API Attributes
|
24
|
+
|
25
|
+
We patch ActiveRecord::Base and Array with a serializer method. You can simple call `.serialize` to see this in action. If you want to customize the attributes that are serialized, simple add an `api_attributes` method to your model:
|
26
|
+
|
27
|
+
|
28
|
+
class Post < ActiveRecord::Base
|
29
|
+
...
|
30
|
+
def api_attributes
|
31
|
+
{
|
32
|
+
id: self.id.to_s,
|
33
|
+
title: self.title.to_s,
|
34
|
+
body: self.body.to_s,
|
35
|
+
created_at: self.created_at.to_s,
|
36
|
+
author: self.user.api_attributes,
|
37
|
+
}
|
38
|
+
end
|
39
|
+
...
|
40
|
+
end
|
41
|
+
|
42
|
+
Adding the `api_attributes` method will allow you to control and customize the out attributes. Also note that you can have associated models, in this case Author attribute is an associated model User. We'll need to add the `api_attributes` to that model also.
|
43
|
+
|
44
|
+
|
45
|
+
### JSON Output Helper
|
46
|
+
|
47
|
+
After you have setup your custom API attributes, you can easily output JSON with a few helper methods:
|
48
|
+
|
49
|
+
#### JSON Model
|
50
|
+
Output a model in JSON:
|
51
|
+
|
52
|
+
post = Post.find(params[:id])
|
53
|
+
json_model :accepted, post
|
54
|
+
|
55
|
+
It's that simple. This will automatically serialize and output your model as JSON. Notice the `:accepted` attribute, this will set the Header Status Code to 202. You can always modify this, take a look at (this nice list of Rails HTTP Status Codes)[http://www.codyfauser.com/2008/7/4/rails-http-status-code-to-symbol-mapping] for more details.
|
56
|
+
|
57
|
+
You can optionally pass parameters by simple adding them to your `json_model` method:
|
58
|
+
|
59
|
+
post = Post.find(params[:id])
|
60
|
+
json_model :accepted, post, param: "Some extra parameters", more: "And some more..."
|
61
|
+
|
62
|
+
You can also append full serialized objects:
|
63
|
+
|
64
|
+
post = Post.find(params[:id])
|
65
|
+
json_model :accepted, post, comments: post.comments.serialize
|
66
|
+
|
67
|
+
In this case we called `post.comments.serialize`, which will actually collect all the objects in the array or ActiveRecord collection and serialize each one based on the API Attributes (if available) or just to_json.
|
68
|
+
|
69
|
+
|
70
|
+
#### JSON Models
|
71
|
+
|
72
|
+
Similar to the json_model method, there is a json_models method. This is simple:
|
73
|
+
|
74
|
+
posts = Posts.all
|
75
|
+
json_models :accepted, posts
|
76
|
+
|
77
|
+
Similarly, you can append additional parameters:
|
78
|
+
|
79
|
+
posts = Posts.all
|
80
|
+
json_models :accepted, posts, categories: Category.all.serialize, tags: Tag.all.serialize
|
81
|
+
|
82
|
+
|
83
|
+
#### Success and Error
|
84
|
+
|
85
|
+
You can create simple success and errors with a few helps. To create a successful JSON response, simple call:
|
86
|
+
|
87
|
+
# json_success message, hash={}
|
88
|
+
json_success "Great success!", extra_params: hash
|
89
|
+
# => { success: "true", message: "message...", ... additional params ... }
|
90
|
+
|
91
|
+
This will automatically send a 200 Ok response in the Header Status Code.
|
92
|
+
|
93
|
+
Error codes are similar:
|
94
|
+
|
95
|
+
# json_error code, message, metadata={}
|
96
|
+
json_error 404, "Post not found.", errors: "Whatever extra metadata and params"
|
97
|
+
# => { error: { message: "Message goes here", code: 404, meta_data: "goes here..." } }
|
98
|
+
|
99
|
+
And this will automatically add your status code to the HTTP response
|
100
|
+
|
22
101
|
|
23
102
|
## Contributing
|
24
103
|
|
@@ -0,0 +1,80 @@
|
|
1
|
+
module JsonSerializer
|
2
|
+
module JsonResponses
|
3
|
+
|
4
|
+
|
5
|
+
# JSON helpers
|
6
|
+
# Simple methods for DRYing up and standardizing JSON output
|
7
|
+
# ----------------------------------------------------------------------------------------------------
|
8
|
+
|
9
|
+
# a nice standard response schema for json
|
10
|
+
def json_response(type, hash = {})
|
11
|
+
# we require one of these types
|
12
|
+
unless [ :ok, :redirect, :error ].include?(type)
|
13
|
+
raise "Invalid json response type: #{type}"
|
14
|
+
end
|
15
|
+
|
16
|
+
# To keep the structure consistent, we'll build the json
|
17
|
+
# structure with these default properties.
|
18
|
+
default_json = {
|
19
|
+
:status => type,
|
20
|
+
:html => nil,
|
21
|
+
:notice => nil,
|
22
|
+
:to => nil
|
23
|
+
}.merge(hash)
|
24
|
+
return default_json
|
25
|
+
end
|
26
|
+
|
27
|
+
# render our standardized json response
|
28
|
+
def render_json_response(type, hash = {})
|
29
|
+
render :json => json_response(type, hash)
|
30
|
+
end
|
31
|
+
|
32
|
+
|
33
|
+
|
34
|
+
# Response specific helper: For Success and error handling
|
35
|
+
# ----------------------------------------------------------------------------------------------------
|
36
|
+
|
37
|
+
# helper for success messages (for actions like delete which dont return models)
|
38
|
+
def json_success message, hash = {}
|
39
|
+
json = {
|
40
|
+
:success => true,
|
41
|
+
:message => message
|
42
|
+
}.merge(hash)
|
43
|
+
render :json => json, status: :accepted
|
44
|
+
end
|
45
|
+
|
46
|
+
# helper for returning failure messages in a common format
|
47
|
+
def json_error code, message=nil, metadata={}
|
48
|
+
render :json => {
|
49
|
+
:error => metadata.merge({
|
50
|
+
:message => message || t("api.errors.#{code}"),
|
51
|
+
:code => code
|
52
|
+
}),
|
53
|
+
}, status: code
|
54
|
+
end
|
55
|
+
|
56
|
+
|
57
|
+
|
58
|
+
# JSON Heper for Models
|
59
|
+
# ----------------------------------------------------------------------------------------------------
|
60
|
+
|
61
|
+
# a standard way to return models. if they have errors then we return the error message
|
62
|
+
# this is a DRY approach to creating and updating and then returning JSON responses
|
63
|
+
def json_model status, model, extra_params={}
|
64
|
+
render json: model.serialize.merge(extra_params), status: status
|
65
|
+
end
|
66
|
+
|
67
|
+
# a standard way to return an array of models
|
68
|
+
# arrays of models are passed back in a data object, this is so we can add things we may need in the future such as pagination
|
69
|
+
def json_models status, models, extra_params={}
|
70
|
+
render json: models.serialize.merge(extra_params), status: status
|
71
|
+
end
|
72
|
+
|
73
|
+
|
74
|
+
end
|
75
|
+
end
|
76
|
+
|
77
|
+
class ActionController::Base
|
78
|
+
include JsonSerializer
|
79
|
+
include JsonSerializer::JsonResponses
|
80
|
+
end
|
@@ -0,0 +1,19 @@
|
|
1
|
+
module ActiveRecord
|
2
|
+
class Base
|
3
|
+
def serialize
|
4
|
+
{"#{self.class.name.downcase.underscore}" => self.send((self.respond_to? :api_attributes) ? :api_attributes : :to_json)}
|
5
|
+
end
|
6
|
+
|
7
|
+
def self.serialize
|
8
|
+
self.collect{|model| model.send((model.respond_to? :api_attributes) ? :api_attributes : :to_json).merge({:_class_name => self.first.class.name.downcase.pluralize})}.group_by{|d| d[:_class_name] }
|
9
|
+
end
|
10
|
+
|
11
|
+
end
|
12
|
+
end
|
13
|
+
|
14
|
+
|
15
|
+
class Array
|
16
|
+
def serialize
|
17
|
+
self.collect{|model| model.send((model.respond_to? :api_attributes) ? :api_attributes : :to_json).merge({:_class_name => self.first.class.name.downcase.pluralize})}.group_by{|d| d[:_class_name] }
|
18
|
+
end
|
19
|
+
end
|
metadata
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: json_serializer
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version: 0.0
|
4
|
+
version: 0.1.0
|
5
5
|
prerelease:
|
6
6
|
platform: ruby
|
7
7
|
authors:
|
@@ -9,7 +9,7 @@ authors:
|
|
9
9
|
autorequire:
|
10
10
|
bindir: bin
|
11
11
|
cert_chain: []
|
12
|
-
date: 2013-
|
12
|
+
date: 2013-07-30 00:00:00.000000000 Z
|
13
13
|
dependencies:
|
14
14
|
- !ruby/object:Gem::Dependency
|
15
15
|
name: bundler
|
@@ -57,6 +57,8 @@ files:
|
|
57
57
|
- Rakefile
|
58
58
|
- json_serializer.gemspec
|
59
59
|
- lib/json_serializer.rb
|
60
|
+
- lib/json_serializer/json_responses.rb
|
61
|
+
- lib/json_serializer/rails/active_record_patch.rb
|
60
62
|
- lib/json_serializer/version.rb
|
61
63
|
homepage: ''
|
62
64
|
licenses:
|