Skip to content

Commit 704927c

Browse files
committed
starting deserializer parsing based on serializer defined attributes
1 parent 1eb321e commit 704927c

File tree

2 files changed

+43
-6
lines changed

2 files changed

+43
-6
lines changed

lib/active_model/deserializer.rb

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,43 @@
11
module ActiveModel
22
module Deserializer
33

4-
def self.included(base)
5-
base.wrap_parameters format: [:json]
4+
def deserialize(resource)
5+
# Defining the Resource and Attributes
6+
@resource = resource
7+
@model = resource.to_s.camelize.constantize
8+
@params = params
9+
self
610
end
711

8-
def deserialize(params)
9-
# TODO deserializaion based on Adapter and Serializer
10-
params
12+
def object
13+
# Return the existing instance of the Resource or initialize a new one
14+
@model.find_or_initialize_by(_params)
15+
end
16+
17+
private
18+
19+
def _params
20+
# Automatically permitting the attributes that should be deserialized
21+
@serializer = get_serializer_for(@model)
22+
@params.require(@resource).permit(@serializer._deserialize)
23+
end
24+
25+
# (WIP)Replicated code just for testing for now
26+
def serializers_cache
27+
@serializers_cache ||= ThreadSafe::Cache.new
28+
end
29+
30+
def get_serializer_for(klass)
31+
serializers_cache.fetch_or_store(klass) do
32+
serializer_class_name = "#{klass.name}Serializer"
33+
serializer_class = serializer_class_name.safe_constantize
34+
35+
if serializer_class
36+
serializer_class
37+
elsif klass.superclass
38+
get_serializer_for(klass.superclass)
39+
end
40+
end
1141
end
1242

1343
end

lib/active_model/serializer.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ class Serializer
1010

1111
class << self
1212
attr_accessor :_attributes
13+
attr_accessor :_deserialize
1314
attr_accessor :_attributes_keys
1415
attr_accessor :_associations
1516
attr_accessor :_urls
@@ -24,13 +25,19 @@ class << self
2425

2526
def self.inherited(base)
2627
base._attributes = self._attributes.try(:dup) || []
27-
base._attributes_keys = self._attributes_keys.try(:dup) || {}
2828
base._associations = self._associations.try(:dup) || {}
29+
base._attributes_keys = self._attributes_keys.try(:dup) || {}
30+
base._deserialize = self._attributes.try(:dup) || []
2931
base._urls = []
3032
serializer_file = File.open(caller.first[/^[^:]+/])
3133
base._cache_digest = Digest::MD5.hexdigest(serializer_file.read)
3234
end
3335

36+
def self.deserialize(*attrs)
37+
@_deserialize.concat attrs
38+
@_deserialize.uniq!
39+
end
40+
3441
def self.attributes(*attrs)
3542
attrs = attrs.first if attrs.first.class == Array
3643
@_attributes.concat attrs

0 commit comments

Comments
 (0)