Class: HALPresenter::Property

Inherits:
Object
  • Object
show all
Defined in:
lib/hal_presenter/property.rb

Direct Known Subclasses

Curies::Curie, Embedded::Embed, Links::Link

Constant Summary collapse

NO_VALUE =
Object.new.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, value = NO_VALUE, **kwargs, &block) ⇒ Property

Returns a new instance of Property.



9
10
11
12
13
14
15
# File 'lib/hal_presenter/property.rb', line 9

def initialize(name, value = NO_VALUE, **kwargs, &block)
  @name = name.to_sym
  @value = value.freeze
  @embed_depth = kwargs[:embed_depth].freeze
  @context = kwargs[:context]
  @lazy = block_given? ? LazyEvaluator.new(block, @context) : nil
end

Instance Attribute Details

#embed_depthObject (readonly)

Returns the value of attribute embed_depth.



7
8
9
# File 'lib/hal_presenter/property.rb', line 7

def embed_depth
  @embed_depth
end

#nameObject (readonly)

Returns the value of attribute name.



7
8
9
# File 'lib/hal_presenter/property.rb', line 7

def name
  @name
end

Instance Method Details

#change_context(context) ⇒ Object



33
34
35
36
37
# File 'lib/hal_presenter/property.rb', line 33

def change_context(context)
  @context = context
  @lazy.update_context(context) if @lazy
  self
end

#nested_depth_ok?(level) ⇒ Boolean

Returns:

  • (Boolean)


39
40
41
42
# File 'lib/hal_presenter/property.rb', line 39

def nested_depth_ok?(level)
  return true unless embed_depth
  level <= embed_depth
end

#value(resource = nil, options = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/hal_presenter/property.rb', line 17

def value(resource = nil, options = {})
  if @lazy
    @lazy.evaluate(resource, options)
  elsif @value != NO_VALUE
    @value
  elsif resource&.respond_to? name_without_curie
    resource.public_send(name_without_curie)
  else
    raise ArgumentError, <<~ERR
      Cannot serialize #{name.inspect}.
      No value given and resource does not respond to #{name_without_curie}. Resource:
      #{resource.inspect}"
      ERR
  end
end