Class: FastJsonapi::Attribute

Inherits:
Object
  • Object
show all
Defined in:
lib/fast_jsonapi/attribute.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key:, method:, options: {}) ⇒ Attribute

Returns a new instance of Attribute.



5
6
7
8
9
# File 'lib/fast_jsonapi/attribute.rb', line 5

def initialize(key:, method:, options: {})
  @key = key
  @method = method
  @conditional_proc = options[:if]
end

Instance Attribute Details

#conditional_procObject (readonly)

Returns the value of attribute conditional_proc.



3
4
5
# File 'lib/fast_jsonapi/attribute.rb', line 3

def conditional_proc
  @conditional_proc
end

#keyObject (readonly)

Returns the value of attribute key.



3
4
5
# File 'lib/fast_jsonapi/attribute.rb', line 3

def key
  @key
end

#methodObject (readonly)

Returns the value of attribute method.



3
4
5
# File 'lib/fast_jsonapi/attribute.rb', line 3

def method
  @method
end

Instance Method Details

#include_attribute?(record, serialization_params) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
25
26
27
# File 'lib/fast_jsonapi/attribute.rb', line 21

def include_attribute?(record, serialization_params)
  if conditional_proc.present?
    conditional_proc.call(record, serialization_params)
  else
    true
  end
end

#serialize(record, serialization_params, output_hash) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/fast_jsonapi/attribute.rb', line 11

def serialize(record, serialization_params, output_hash)
  if include_attribute?(record, serialization_params)
    output_hash[key] = if method.is_a?(Proc)
      method.arity.abs == 1 ? method.call(record) : method.call(record, serialization_params)
    else
      record.public_send(method)
    end
  end
end