class ScopedSerializer::BaseSerializer

Public Instance Methods

as_json(options={}) click to toggle source

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

# 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_hash() click to toggle source
# File lib/scoped_serializer/base_serializer.rb, line 53
def data_hash
  @options[:data] || {}
end
default_root_key(object_class) click to toggle source

Tries to find the default root key.

@example

default_root_key(User) # => 'user'
# 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
meta() click to toggle source
# File lib/scoped_serializer/base_serializer.rb, line 65
def meta
  @options[:meta] || {}
end
meta_hash() click to toggle source
# File lib/scoped_serializer/base_serializer.rb, line 57
def meta_hash
  if meta.present?
    { :meta => meta }
  else
    {}
  end
end
set_scope(scope) click to toggle source

Sets scope and settings based on @options.

# 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={}) click to toggle source

Returns attributes as a CSV string.

# 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={}) click to toggle source

Returns attributes as an XLS string.

# File lib/scoped_serializer/base_serializer.rb, line 82
def to_xls(options={})
  options.merge!(:col_sep => "\t")

  to_csv(options)
end