class Cyrax::Serializers::Scope

Public Class Methods

new(&block) click to toggle source
# File lib/cyrax/serializers/scope.rb, line 3
def initialize(&block)
  @attrs = {}
  @dynamic_attrs = {}
  @relation_attrs = {}
  @namespace_attrs = {}
  @assigned_attrs = {}
  @default_attributes = false
  instance_eval(&block) if block_given?
end

Public Instance Methods

assigned(name, &block) click to toggle source
# File lib/cyrax/serializers/scope.rb, line 17
def assigned(name, &block)
  @assigned_attrs[name] = self.class.new(&block)
end
attribute(attribute, options = {}, &block) click to toggle source
# File lib/cyrax/serializers/scope.rb, line 41
def attribute(attribute, options = {}, &block)
  if block_given?
    @dynamic_attrs[attribute] = block
  else
    @attrs[attribute] = attribute
  end
end
attributes(*attrs) click to toggle source
# File lib/cyrax/serializers/scope.rb, line 35
def attributes(*attrs)
  attrs.map do |attribute|
    attribute(attribute)
  end
end
default_attributes() click to toggle source
# File lib/cyrax/serializers/scope.rb, line 31
def default_attributes
  @default_attributes = true
end
has_many(attribute, &block)
Alias for: relation
has_one(attribute, &block)
Alias for: relation
namespace(name, &block) click to toggle source
# File lib/cyrax/serializers/scope.rb, line 13
def namespace(name, &block)
  @namespace_attrs[name] = self.class.new(&block)
end
relation(attribute, &block) click to toggle source
# File lib/cyrax/serializers/scope.rb, line 21
def relation(attribute, &block)
  if block_given?
    @relation_attrs[attribute] = self.class.new(&block)
  else
    @attrs[attribute] = attribute
  end
end
Also aliased as: has_many, has_one
serialize(resource, options = {}) click to toggle source
# File lib/cyrax/serializers/scope.rb, line 49
def serialize(resource, options = {})
  if resource.nil?
    nil
  elsif resource.respond_to?(:to_a)
    resource.to_a.map{ |r| serialize_one(r, options) }
  else
    serialize_one(resource, options)
  end
end
serialize_one(resource, options = {}) click to toggle source
# File lib/cyrax/serializers/scope.rb, line 59
def serialize_one(resource, options = {})
  result = {}
  if @default_attributes
    result = resource.attributes rescue {}
  end
  @dynamic_attrs.map do |attribute, block|
    result[attribute] = options[:serializer].instance_exec(resource, options, &block)
  end
  @relation_attrs.map do |attribute, scope|
    value = resource.send(attribute)
    result[attribute] = scope.serialize(value, options)
  end
  @assigned_attrs.map do |attribute, scope|
    assignments = options[:assignments] || {}
    value = assignments[attribute]
    result[attribute] = scope.serialize(value, options)
  end
  @namespace_attrs.map do |attribute, scope|
    result[attribute] = scope.serialize(resource, options)
  end
  @attrs.map do |attribute, options|
    result[attribute] = resource.send(attribute)
  end
  result
end