to_api 1.0.2 → 1.0.3
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/to_api.rb +39 -39
- data/spec/spec_helper.rb +1 -0
- metadata +4 -4
data/lib/to_api.rb
CHANGED
@@ -1,48 +1,48 @@
|
|
1
|
-
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
|
6
|
-
|
7
|
-
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
|
12
|
-
|
1
|
+
if Object.const_defined? :ActiveRecord
|
2
|
+
class ActiveRecord::Base
|
3
|
+
def to_api(*includes) #assumes all attribute types are fine
|
4
|
+
hash = {}
|
5
|
+
valid_includes = (self.class.reflect_on_all_associations.map(&:name).map(&:to_s) | self.valid_api_includes)
|
6
|
+
|
7
|
+
include_hash = {}
|
8
|
+
includes.each do |i|
|
9
|
+
if i.kind_of?(Hash)
|
10
|
+
i.each do |k,v|
|
11
|
+
include_hash[k] = v
|
12
|
+
end
|
13
|
+
else
|
14
|
+
include_hash[i] = []
|
13
15
|
end
|
14
|
-
else
|
15
|
-
include_hash[i] = []
|
16
16
|
end
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
22
|
-
|
23
|
-
|
24
|
-
|
25
|
-
end
|
17
|
+
|
18
|
+
include_hash.delete_if{|k,v| !valid_includes.include?(k)}
|
19
|
+
|
20
|
+
attributes.each do |k, v|
|
21
|
+
attribute_includes = include_hash[k] || []
|
22
|
+
v = v.to_api(*attribute_includes) if v.respond_to?(:to_api)
|
23
|
+
hash[k] = v
|
24
|
+
end
|
26
25
|
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
26
|
+
(include_hash.keys-attributes.keys).each do |relation|
|
27
|
+
relation_includes = include_hash[relation] || []
|
28
|
+
api_obj = self.send(relation)
|
29
|
+
hash[relation.to_s] = api_obj.respond_to?(:to_api) ? api_obj.to_api(*relation_includes) : api_obj
|
30
|
+
end
|
31
|
+
|
32
|
+
hash
|
31
33
|
end
|
32
|
-
|
33
|
-
hash
|
34
|
-
end
|
35
34
|
|
36
|
-
|
37
|
-
|
38
|
-
|
35
|
+
# override in models
|
36
|
+
def valid_api_includes
|
37
|
+
[]
|
38
|
+
end
|
39
39
|
end
|
40
|
-
end
|
41
40
|
|
42
|
-
#Sadly, Scope isn't enumerable
|
43
|
-
class ActiveRecord::NamedScope::Scope
|
44
|
-
|
45
|
-
|
41
|
+
#Sadly, Scope isn't enumerable
|
42
|
+
class ActiveRecord::NamedScope::Scope
|
43
|
+
def to_api(*includes)
|
44
|
+
map{|e|e.to_api(*includes)}
|
45
|
+
end
|
46
46
|
end
|
47
47
|
end
|
48
48
|
|
@@ -89,4 +89,4 @@ class NilClass
|
|
89
89
|
def to_api
|
90
90
|
self
|
91
91
|
end
|
92
|
-
end
|
92
|
+
end
|
data/spec/spec_helper.rb
CHANGED
metadata
CHANGED
@@ -1,13 +1,13 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: to_api
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
hash:
|
4
|
+
hash: 17
|
5
5
|
prerelease: false
|
6
6
|
segments:
|
7
7
|
- 1
|
8
8
|
- 0
|
9
|
-
-
|
10
|
-
version: 1.0.
|
9
|
+
- 3
|
10
|
+
version: 1.0.3
|
11
11
|
platform: ruby
|
12
12
|
authors:
|
13
13
|
- Shawn Anderson
|
@@ -36,7 +36,7 @@ dependencies:
|
|
36
36
|
segments:
|
37
37
|
- 3
|
38
38
|
version: "3"
|
39
|
-
type: :
|
39
|
+
type: :development
|
40
40
|
name: activerecord
|
41
41
|
prerelease: false
|
42
42
|
version_requirements: *id001
|