Class: ScopedSerializer::BaseSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/scoped_serializer/base_serializer.rb

Direct Known Subclasses

ArraySerializer, DefaultSerializer, Serializer

Instance Method Summary collapse

Instance Method Details

#as_json(options = {}) ⇒ Object

Returns JSON using serializable_hash which must be implemented on a class. Uses the root key from @options when set.



35
36
37
38
39
40
41
42
43
# File 'lib/scoped_serializer/base_serializer.rb', line 35

def as_json(options={})
  options = @options.merge(options)

  if options[:root]
    { options[:root].to_sym => serializable_hash }.merge(meta_hash)
  else
    serializable_hash
  end
end

#default_root_key(object_class) ⇒ Object

Tries to find the default root key.

Examples:

default_root_key(User) # => 'user'


23
24
25
26
27
28
29
# File 'lib/scoped_serializer/base_serializer.rb', line 23

def default_root_key(object_class)
  if object_class.respond_to?(:model_name)
    object_class.model_name.element
  else
    object_class.name
  end
end

#metaObject



53
54
55
# File 'lib/scoped_serializer/base_serializer.rb', line 53

def meta
  @options[:meta] || {}
end

#meta_hashObject



45
46
47
48
49
50
51
# File 'lib/scoped_serializer/base_serializer.rb', line 45

def meta_hash
  if meta.present?
    { :meta => meta }
  else
    {}
  end
end

#set_scope(scope) ⇒ Object

Sets scope and settings based on @options.



7
8
9
10
11
12
13
14
15
# File 'lib/scoped_serializer/base_serializer.rb', line 7

def set_scope(scope)
  if @options[:associations].present? || @options[:attributes].present?
    @scope = scope.dup
    @scope.attributes *@options[:attributes] if @options[:attributes]
    @scope._association [@options[:associations]] if @options[:associations]
  else
    @scope = scope
  end
end