Class: Encore::Serializer::Base

Inherits:
ActiveModel::Serializer
  • Object
show all
Defined in:
lib/encore/serializer/base.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.always_include(*value) ⇒ Object

Specify which resources the API always include in the “linked” top-level key.



36
37
38
39
40
41
42
# File 'lib/encore/serializer/base.rb', line 36

def self.always_include(*value)
  if value.any?
    @always_include = value.flatten
  else
    @always_include ||= []
  end
end

.can_access(*value) ⇒ Object

Specify which resources the API exposes URL to. Default is can_include + always_include.



46
47
48
49
50
51
52
# File 'lib/encore/serializer/base.rb', line 46

def self.can_access(*value)
  if value.any?
    @can_access = value.flatten
  else
    @can_access ||= can_include | always_include
  end
end

.can_include(*value) ⇒ Object

Specify which resources the API can be included in the “linked” top-level key.



27
28
29
30
31
32
33
# File 'lib/encore/serializer/base.rb', line 27

def self.can_include(*value)
  if value.any?
    @can_include = value.flatten
  else
    @can_include ||= []
  end
end

.key_mappings(value = nil) ⇒ Object



62
63
64
65
66
67
68
# File 'lib/encore/serializer/base.rb', line 62

def self.key_mappings(value = nil)
  if value
    @key_mappings = value
  else
    @key_mappings ||= {}
  end
end

.root_key(value = nil) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/encore/serializer/base.rb', line 54

def self.root_key(value = nil)
  if value
    @root_key = value
  else
    @root_key ||= model_class.name.pluralize.underscore.to_sym
  end
end

Instance Method Details

#idObject



8
9
10
# File 'lib/encore/serializer/base.rb', line 8

def id
  object.id.to_s
end


12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/encore/serializer/base.rb', line 12

def links
  reflections = object.try(:_reflections) || object.reflections
  reflections.each_with_object({}) do |(_, reflection), memo|
    if object.association(reflection.name).loaded?
      fetcher = LinksReflectionIncluder::Loaded
    else
      next unless self.class.can_access.include?(reflection.name)
      fetcher = LinksReflectionIncluder::NotLoaded
    end

    memo.merge!(reflection.name => fetcher.send("reflection_#{reflection.macro}", object, reflection))
  end
end