Class: HALDecorator::Property

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

Direct Known Subclasses

Embedded::Embed, Links::Link

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, value = nil, &block) ⇒ Property

Returns a new instance of Property.



7
8
9
10
11
12
13
14
# File 'lib/hal_decorator/property.rb', line 7

def initialize(name, value = nil, &block)
  @name = name
  @value = value
  @scope = nil
  return unless block_given?
  @scope = eval 'self', block.binding
  define_singleton_method(:value_from_block, &block)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/hal_decorator/property.rb', line 35

def method_missing(method, *args, &block)
  if scope&.respond_to? method
    define_singleton_method(method) { |*a, &b| scope.public_send method, *a, &b }
    return public_send(method, *args, &block)
  end
  super
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/hal_decorator/property.rb', line 3

def name
  @name
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/hal_decorator/property.rb', line 3

def options
  @options
end

#resourceObject (readonly) Also known as: resources

Returns the value of attribute resource.



3
4
5
# File 'lib/hal_decorator/property.rb', line 3

def resource
  @resource
end

Instance Method Details

#change_scope(new_scope) ⇒ Object



30
31
32
33
# File 'lib/hal_decorator/property.rb', line 30

def change_scope(new_scope)
  return unless scope
  @scope = new_scope
end

#respond_to_missing?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
46
# File 'lib/hal_decorator/property.rb', line 43

def respond_to_missing?(method, include_private = false)
  return true if scope&.respond_to? method
  super
end

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



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/hal_decorator/property.rb', line 16

def value(resource = nil, options = {})
  @resource = resource
  @options = options
  if scope
    value_from_block
  elsif resource && @value.nil?
    resource.public_send(name) if resource.respond_to?(name)
  else
    @value
  end
ensure
  reset
end