Class: FastJsonapi::Scalar

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

Direct Known Subclasses

Attribute, Link

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Scalar.



5
6
7
8
9
# File 'lib/fast_jsonapi/scalar.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/scalar.rb', line 3

def conditional_proc
  @conditional_proc
end

#keyObject (readonly)

Returns the value of attribute key.



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

def key
  @key
end

#methodObject (readonly)

Returns the value of attribute method.



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

def method
  @method
end

Instance Method Details

#conditionally_allowed?(record, serialization_params) ⇒ Boolean

Returns:

  • (Boolean)


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

def conditionally_allowed?(record, serialization_params)
  if conditional_proc.present?
    FastJsonapi.call_proc(conditional_proc, 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/scalar.rb', line 11

def serialize(record, serialization_params, output_hash)
  if conditionally_allowed?(record, serialization_params)
    if method.is_a?(Proc)
      output_hash[key] = FastJsonapi.call_proc(method, record, serialization_params)
    else
      output_hash[key] = record.public_send(method)
    end
  end
end