@@ -126,6 +126,57 @@ def success?
126
126
true
127
127
end
128
128
129
+ # @return [Hash] containing the attributes and first level
130
+ # associations, similar to how ActiveModel::Serializers::JSON is used
131
+ # in ActiveRecord::Base.
132
+ #
133
+ # TODO: Move to here the Attributes adapter logic for
134
+ # +serializable_hash_for_single_resource(options)+
135
+ # and include <tt>ActiveModel::Serializers::JSON</tt>.
136
+ # So that the below is true:
137
+ # @param options [nil, Hash] The same valid options passed to `serializable_hash`
138
+ # (:only, :except, :methods, and :include).
139
+ #
140
+ # See
141
+ # https://github.com/rails/rails/blob/v5.0.0.beta2/activemodel/lib/active_model/serializers/json.rb#L17-L101
142
+ # https://github.com/rails/rails/blob/v5.0.0.beta2/activemodel/lib/active_model/serialization.rb#L85-L123
143
+ # https://github.com/rails/rails/blob/v5.0.0.beta2/activerecord/lib/active_record/serialization.rb#L11-L17
144
+ # https://github.com/rails/rails/blob/v5.0.0.beta2/activesupport/lib/active_support/core_ext/object/json.rb#L147-L162
145
+ #
146
+ # @example
147
+ # # The :only and :except options can be used to limit the attributes included, and work
148
+ # # similar to the attributes method.
149
+ # serializer.as_json(only: [:id, :name])
150
+ # serializer.as_json(except: [:id, :created_at, :age])
151
+ #
152
+ # # To include the result of some method calls on the model use :methods:
153
+ # serializer.as_json(methods: :permalink)
154
+ #
155
+ # # To include associations use :include:
156
+ # serializer.as_json(include: :posts)
157
+ # # Second level and higher order associations work as well:
158
+ # serializer.as_json(include: { posts: { include: { comments: { only: :body } }, only: :title } })
159
+ def serializable_hash ( adapter_opts = nil )
160
+ adapter_opts ||= { }
161
+ adapter_opts = { include : '*' , adapter : :attributes } . merge! ( adapter_opts )
162
+ adapter = ActiveModelSerializers ::Adapter . create ( self , adapter_opts )
163
+ adapter . serializable_hash ( adapter_opts )
164
+ end
165
+ alias to_hash serializable_hash
166
+ alias to_h serializable_hash
167
+
168
+ # @see #serializable_hash
169
+ # TODO: When moving attributes adapter logic here, @see #serializable_hash
170
+ # So that the below is true:
171
+ # @param options [nil, Hash] The same valid options passed to `as_json`
172
+ # (:root, :only, :except, :methods, and :include).
173
+ # The default for `root` is nil.
174
+ # The default value for include_root is false. You can change it to true if the given
175
+ # JSON string includes a single root node.
176
+ def as_json ( adapter_opts = nil )
177
+ serializable_hash ( adapter_opts )
178
+ end
179
+
129
180
# Used by adapter as resource root.
130
181
def json_key
131
182
root || object . class . model_name . to_s . underscore
0 commit comments