class FTL::Serializer::Base
Attributes
collection[R]
obj[RW]
Public Class Methods
new(collection, args = {})
click to toggle source
# File lib/ftl/serializer/base.rb, line 13 def initialize(collection, args = {}) @collection = collection @locals = args.dig(:locals) end
Public Instance Methods
links(hash)
click to toggle source
# File lib/ftl/serializer/base.rb, line 35 def links(hash) self.tap { @links = hash } end
locals(*args)
click to toggle source
# File lib/ftl/serializer/base.rb, line 43 def locals(*args) if args.size == 0 return @_locals if defined? @_locals return nil if @locals.blank? @_locals = begin local_methods = @locals.keys.map(&:to_sym) values = @locals.values if local_methods.any? Struct.new(*local_methods).new(*values) end rescue raise FTL::Errors::LocalsError.new(self.class.name) end else self.tap { @locals = args[0] } end end
meta(hash)
click to toggle source
# File lib/ftl/serializer/base.rb, line 31 def meta(hash) self.tap { @meta = hash } end
root(name)
click to toggle source
# File lib/ftl/serializer/base.rb, line 39 def root(name) self.tap { @root = name } end
to_h()
click to toggle source
# File lib/ftl/serializer/base.rb, line 18 def to_h if singular_object? rootify(singular_to_h) else rootify(multi_to_h) end end
Also aliased as: to_hash
to_json()
click to toggle source
# File lib/ftl/serializer/base.rb, line 27 def to_json Oj.dump(to_h) end
Private Instance Methods
format_root_name(root_name)
click to toggle source
# File lib/ftl/serializer/base.rb, line 93 def format_root_name(root_name) if self.class.camel_case? root_name.to_s.camelize(:lower) else root_name.to_s end end
merge!(hash)
click to toggle source
# File lib/ftl/serializer/base.rb, line 105 def merge!(hash) return hash if self.class.object_merge.empty? self.class.object_merge.reduce(hash) do |complete_hash, merge_object_method| new_hash = self.send(merge_object_method) complete_hash.merge(new_hash) end end
meta_hash()
click to toggle source
# File lib/ftl/serializer/base.rb, line 101 def meta_hash [{ "meta" => @meta, "links" => @links }.select { |_, value| !value.nil? }] end
multi_to_h()
click to toggle source
# File lib/ftl/serializer/base.rb, line 72 def multi_to_h collection.map do |object| self.obj = object hashify end end
rootify(hash)
click to toggle source
# File lib/ftl/serializer/base.rb, line 79 def rootify(hash) root_name = @root || self.class.root_name return hash if root_name == :disabled || root_name.nil? root_name = format_root_name(root_name) if singular_object? { root_name => hash } else { root_name.pluralize => hash }.tap do |h| meta_hash.map { |meta| h.merge!(meta) if meta } end end end
singular_object?()
click to toggle source
# File lib/ftl/serializer/base.rb, line 63 def singular_object? collection.is_a?(Hash) || collection.is_a?(Struct) || !collection.respond_to?(:map) end
singular_to_h()
click to toggle source
# File lib/ftl/serializer/base.rb, line 67 def singular_to_h self.obj = collection hashify end