has_response 0.0.1 → 0.0.2
Sign up to get free protection for your applications and to get access to all the features.
- data/app/concerns/has_response.rb +48 -0
- data/lib/has_response/version.rb +1 -1
- metadata +2 -1
@@ -0,0 +1,48 @@
|
|
1
|
+
module HasResponse
|
2
|
+
extend ActiveSupport::Concern
|
3
|
+
|
4
|
+
def to_response_with(*attributes)
|
5
|
+
raise "Class `#{self.class.name}' does not have a `to_response' method defined" if !respond_to?(:to_response)
|
6
|
+
response = self.to_response
|
7
|
+
attributes.each do |attribute|
|
8
|
+
if attribute.is_a?(Hash)
|
9
|
+
attribute.each do |key, value|
|
10
|
+
response[format_response_key(key)] = format_response_value(self.send(key), value)
|
11
|
+
end
|
12
|
+
elsif attribute.is_a?(Array)
|
13
|
+
attribute.each do |key|
|
14
|
+
response[format_response_key(key)] = format_response_value(self.send(key))
|
15
|
+
end
|
16
|
+
elsif attribute.is_a?(Symbol)
|
17
|
+
response[format_response_key(attribute)] = format_response_value(self.send(attribute))
|
18
|
+
end
|
19
|
+
end
|
20
|
+
response
|
21
|
+
end
|
22
|
+
|
23
|
+
protected
|
24
|
+
|
25
|
+
def format_response_key(key)
|
26
|
+
key = key.to_s
|
27
|
+
key.sub!(/\?$/, '')
|
28
|
+
key.to_sym
|
29
|
+
end
|
30
|
+
|
31
|
+
def format_response_value(value, with=nil)
|
32
|
+
if value.nil?
|
33
|
+
nil
|
34
|
+
elsif value.is_a?(TrueClass) || value.is_a?(FalseClass) || value.is_a?(String) || value.is_a?(Symbol) || value.is_a?(Integer)
|
35
|
+
value
|
36
|
+
elsif value.is_a?(ActiveRecord::Relation) || value.is_a?(Array)
|
37
|
+
format_response_collection(value, with)
|
38
|
+
else
|
39
|
+
with.nil? ? value.to_response : value.to_response_with(with)
|
40
|
+
end
|
41
|
+
end
|
42
|
+
|
43
|
+
def format_response_collection(collection, with=nil)
|
44
|
+
collection.collect do |record|
|
45
|
+
with.nil? ? record.to_response : record.to_response_with(with)
|
46
|
+
end
|
47
|
+
end
|
48
|
+
end
|
data/lib/has_response/version.rb
CHANGED
metadata
CHANGED
@@ -1,7 +1,7 @@
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
2
2
|
name: has_response
|
3
3
|
version: !ruby/object:Gem::Version
|
4
|
-
version: 0.0.
|
4
|
+
version: 0.0.2
|
5
5
|
prerelease:
|
6
6
|
platform: ruby
|
7
7
|
authors:
|
@@ -82,6 +82,7 @@ executables: []
|
|
82
82
|
extensions: []
|
83
83
|
extra_rdoc_files: []
|
84
84
|
files:
|
85
|
+
- app/concerns/has_response.rb
|
85
86
|
- lib/has_response/version.rb
|
86
87
|
- lib/has_response.rb
|
87
88
|
- MIT-LICENSE
|