class Apia::Definitions::Field

Attributes

array[RW]
backend[RW]
condition[RW]
description[RW]
include[RW]
null[RW]
type[W]

Public Class Methods

new(name, id: nil) click to toggle source
# File lib/apia/definitions/field.rb, line 22
def initialize(name, id: nil)
  @name = name
  @id = id
end

Public Instance Methods

array?() click to toggle source

Is the result from this field expected to be an array?

@return [Boolean]

# File lib/apia/definitions/field.rb, line 44
def array?
  @array == true
end
dsl() click to toggle source

Return a DSL instance for this field

@return [Apia::DSLs::Field]

# File lib/apia/definitions/field.rb, line 62
def dsl
  @dsl ||= DSLs::Field.new(self)
end
include?(value, request) click to toggle source

Should this field be inclued for the given value and request

@param value [Object] @param request [Apia::Request] @return [Boolean]

# File lib/apia/definitions/field.rb, line 53
def include?(value, request)
  return true if @condition.nil?

  @condition.call(value, request) == true
end
null?() click to toggle source

Can the result for thsi field be nil?

@return [Boolean]

# File lib/apia/definitions/field.rb, line 37
def null?
  @null == true
end
raw_value_from_object(object) click to toggle source

Return the backend value from the given object based on the rules that exist for this field.

@param object [Object] @return [Object]

# File lib/apia/definitions/field.rb, line 71
def raw_value_from_object(object)
  if @backend
    get_value_from_backend(object)
  else
    get_value_directly_from_object(object, @name)
  end
end
type() click to toggle source

Return the type of object

@return [Class]

# File lib/apia/definitions/field.rb, line 30
def type
  Type.new(@type)
end
value(object, request: nil, path: []) click to toggle source

Return an instance of a Type or a Scalar for this field

@param object [Object] @return [Object]

# File lib/apia/definitions/field.rb, line 83
def value(object, request: nil, path: [])
  raw_value = raw_value_from_object(object)

  return nil if raw_value.nil? && null?
  raise Apia::NullFieldValueError.new(self, object) if raw_value.nil?

  if array? && raw_value.is_a?(Array)
    raw_value.map { |v| type.cast(v, request: request, path: path) }
  else
    type.cast(raw_value, request: request, path: path)
  end
end

Private Instance Methods

get_value_directly_from_object(object, name) click to toggle source
# File lib/apia/definitions/field.rb, line 107
def get_value_directly_from_object(object, name)
  if object.is_a?(Hash)
    object.fetch(name.to_sym) { object[name.to_s] }
  else
    object.public_send(name.to_sym)
  end
end
get_value_from_backend(object) click to toggle source
# File lib/apia/definitions/field.rb, line 98
def get_value_from_backend(object)
  case @backend
  when Symbol
    get_value_directly_from_object(object, @backend)
  when Proc
    @backend.call(object)
  end
end