lib/fields/serializer/fields_tree.rb in fields-serializer-0.8.5 vs lib/fields/serializer/fields_tree.rb in fields-serializer-0.9.0
- old
+ new
@@ -1,6 +1,6 @@
-require 'active_record'
+require "active_record"
require "active_model_serializers"
module Fields
module Serializer
@@ -11,16 +11,16 @@
def initialize(klass)
@klass = klass
@fields = []
@associations = {}
end
-
+
# Self if any fields or associations. Nil otherwise
def presence
self if fields.present? || associations.present?
end
-
+
# Adds a new field (json api notation) to the tree structure:
#
# user_tree.notation
# #=> [:name, :surname, { subjects: [:title, { posts: { comments: :count } }], followers: :nickname }]
#
@@ -31,11 +31,11 @@
return self if join_field.blank?
parent, rest = join_field.to_s.split(".", 2)
rest.present? ? add_association!(parent, rest) : add_field!(parent)
self
end
-
+
# Return the tree structure in Rails includes notation including both associations and fields
#
# user_tree.notation
# #=> [:name, :surname, { subjects: [:title, { posts: :comments }], followers: :nickname }]
#
@@ -62,17 +62,17 @@
add_association_to_includes!(result, association_name)
end
end.presence
Array.wrap(to_includes).one? ? to_includes.first : to_includes
end
-
+
def to_s
notation.to_s
end
-
+
private
-
+
def add_association!(parent, rest)
existing_association?(parent) ? merge_association!(parent, rest) : append_association!(parent, rest)
end
def add_association_includes_to_includes!(includes, association_name, association_includes)
@@ -98,22 +98,22 @@
def add_field!(value)
fields << value if new_field?(value)
end
def association?(value)
- klass.reflections.keys.include?(value)
+ klass.reflections.key?(value)
end
-
+
def associations_to_notation
associations.inject({}) do |result, (k, v)|
result.merge!(k => v.notation)
end
end
-
+
def existing_association?(value)
!!associations[value]
end
-
+
def existing_field?(value)
fields.include?(value)
end
def merge_association!(key, fields)