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.



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

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

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

#data_hashObject



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

def data_hash
  @options[:data] || {}
end

#default_root_key(object_class) ⇒ Object

Tries to find the default root key.

Examples:

default_root_key(User) # => 'user'


25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/scoped_serializer/base_serializer.rb', line 25

def default_root_key(object_class)
  if (serializer = ScopedSerializer.find_serializer_by_class(object_class))
    root_key = serializer.find_scope(:default).options[:root]
  end

  if root_key
    root_key.to_s
  elsif object_class.respond_to?(:model_name)
    object_class.model_name.element
  else
    object_class.name
  end
end

#metaObject



65
66
67
# File 'lib/scoped_serializer/base_serializer.rb', line 65

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

#meta_hashObject



57
58
59
60
61
62
63
# File 'lib/scoped_serializer/base_serializer.rb', line 57

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

#set_scope(scope) ⇒ Object

Sets scope and settings based on @options.



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

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

#to_csv(options = {}) ⇒ Object

Returns attributes as a CSV string.



72
73
74
75
76
77
# File 'lib/scoped_serializer/base_serializer.rb', line 72

def to_csv(options={})
  CSV.generate(options) do |csv|
    csv << scope.attributes
    csv << attributes_hash.values
  end
end

#to_xls(options = {}) ⇒ Object

Returns attributes as an XLS string.



82
83
84
85
86
# File 'lib/scoped_serializer/base_serializer.rb', line 82

def to_xls(options={})
  options.merge!(:col_sep => "\t")

  to_csv(options)
end