Class: Nanoc2::Proxy

Inherits:
Object
  • Object
show all
Defined in:
lib/nanoc2/base/proxy.rb

Overview

Nanoc2::Proxy is used when making data available to pages and layouts. It provides an easy way to access data without the risk of accidentally calling destructive methods.

Instance Method Summary collapse

Constructor Details

#initialize(obj) ⇒ Proxy

Creates a proxy for the given object.



11
12
13
# File 'lib/nanoc2/base/proxy.rb', line 11

def initialize(obj)
  @obj = obj
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

Used for requesting attributes without accessing the proxy like a hash.



31
32
33
# File 'lib/nanoc2/base/proxy.rb', line 31

def method_missing(method, *args)
  self[method]
end

Instance Method Details

#[](key) ⇒ Object

Requests the attribute with the given name. key can be a string or a symbol, and it can contain a trailing question mark (which will be stripped).



18
19
20
21
22
# File 'lib/nanoc2/base/proxy.rb', line 18

def [](key)
  real_key = key.to_s.sub(/\?$/, '').to_sym

  @obj.attribute_named(real_key)
end

#[]=(key, value) ⇒ Object

Sets a given attribute. The use of setting an object’s attributes is not recommended but may be necessary in some cases.



26
27
28
# File 'lib/nanoc2/base/proxy.rb', line 26

def []=(key, value)
  @obj.attributes[key.to_sym] = value
end