Class: FTL::Serializer::Base

Inherits:
Object
  • Object
show all
Extended by:
DSL
Defined in:
lib/ftl/serializer/base.rb

Instance Attribute Summary collapse

Attributes included from DSL

#attribute_list, #object_merge

Attributes included from DSL::Format

#root_name

Instance Method Summary collapse

Methods included from DSL

attributes, define_to_h, inherited, merge_with

Methods included from DSL::Format

#camel_case?, #format, #hash_format

Constructor Details

#initialize(collection, args = {}) ⇒ Base



13
14
15
16
# File 'lib/ftl/serializer/base.rb', line 13

def initialize(collection, args = {})
  @collection = collection
  @locals = args.dig(:locals)
end

Instance Attribute Details

#collectionObject (readonly)

Returns the value of attribute collection.



11
12
13
# File 'lib/ftl/serializer/base.rb', line 11

def collection
  @collection
end

#objObject

Returns the value of attribute obj.



10
11
12
# File 'lib/ftl/serializer/base.rb', line 10

def obj
  @obj
end

Instance Method Details



35
36
37
# File 'lib/ftl/serializer/base.rb', line 35

def links(hash)
  self.tap { @links = hash }
end

#locals(*args) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# 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) ⇒ Object



31
32
33
# File 'lib/ftl/serializer/base.rb', line 31

def meta(hash)
  self.tap { @meta = hash }
end

#root(name) ⇒ Object



39
40
41
# File 'lib/ftl/serializer/base.rb', line 39

def root(name)
  self.tap { @root = name }
end

#to_hObject Also known as: to_hash



18
19
20
21
22
23
24
# 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

#to_jsonObject



27
28
29
# File 'lib/ftl/serializer/base.rb', line 27

def to_json
  Oj.dump(to_h)
end