Class: RubySerializer::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_serializer/field.rb

Direct Known Subclasses

Association

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(field, namespace, options) ⇒ Field

Returns a new instance of Field.



6
7
8
9
10
11
12
13
14
# File 'lib/ruby_serializer/field.rb', line 6

def initialize(field, namespace, options)
  @field     = field.to_sym
  @as        = options[:as]   || @field
  @from      = options[:from] || @field
  @value     = options[:value]
  @only      = options[:only]
  @unless    = options[:unless]
  @namespace = namespace.dup
end

Instance Attribute Details

#asObject (readonly)

Returns the value of attribute as.



4
5
6
# File 'lib/ruby_serializer/field.rb', line 4

def as
  @as
end

#fieldObject (readonly)

Returns the value of attribute field.



4
5
6
# File 'lib/ruby_serializer/field.rb', line 4

def field
  @field
end

#fromObject (readonly)

Returns the value of attribute from.



4
5
6
# File 'lib/ruby_serializer/field.rb', line 4

def from
  @from
end

#namespaceObject (readonly)

Returns the value of attribute namespace.



4
5
6
# File 'lib/ruby_serializer/field.rb', line 4

def namespace
  @namespace
end

#valueObject (readonly)

Returns the value of attribute value.



4
5
6
# File 'lib/ruby_serializer/field.rb', line 4

def value
  @value
end

Instance Method Details

#only?(resource, serializer) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ruby_serializer/field.rb', line 30

def only?(resource, serializer)
  case @only
  when nil    then true
  when true   then true
  when false  then false
  when Symbol then resource.send(@only)
  when Proc   then serializer.instance_exec(&@only)
  else
    raise ArgumentError, "unexpected #{@only}"
  end
end

#present?(resource, serializer) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/ruby_serializer/field.rb', line 26

def present?(resource, serializer)
  only?(resource, serializer) && !unless?(resource, serializer)
end

#serialize(resource, serializer) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/ruby_serializer/field.rb', line 16

def serialize(resource, serializer)
  case value
  when nil    then resource.send(from)
  when Symbol then resource.send(value)
  when Proc   then serializer.instance_exec(&value)
  else
    value
  end
end

#unless?(resource, serializer) ⇒ Boolean

Returns:

  • (Boolean)


42
43
44
45
46
47
48
49
50
51
52
# File 'lib/ruby_serializer/field.rb', line 42

def unless?(resource, serializer)
  case @unless
  when nil    then false
  when true   then true
  when false  then false
  when Symbol then resource.send(@unless)
  when Proc   then serializer.instance_exec(&@unless)
  else
    raise ArgumentError, "unexpected #{@unless}"
  end
end