Class: PropertyString

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

Defined Under Namespace

Classes: MethodNotAllowed

Constant Summary collapse

VERSION =
"0.0.2"
KEY_NOT_FOUND =
"__#{object_id}-not-found-placeholder-#{object_id}__"

Instance Method Summary collapse

Constructor Details

#initialize(object, options = nil) ⇒ PropertyString

Returns a new instance of PropertyString.



14
15
16
17
18
19
20
# File 'lib/property_string.rb', line 14

def initialize(object, options = nil)
  @object = object

  @options = (options || {}).dup
  @options[:raise_if_method_missing] = true unless @options.include?(:raise_if_method_missing)
  @options[:whitelist] = @options[:whitelist] || {}
end

Instance Method Details

#[](property) ⇒ Object



22
23
24
25
26
# File 'lib/property_string.rb', line 22

def [](property)
  value = fetch_property_chain(property)
  value = nil if value == KEY_NOT_FOUND
  value
end

#fetch(property, *default, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/property_string.rb', line 28

def fetch(property, *default, &block)
  fetch_default = -> do
    raise KeyError, "property #{property} not found" unless default.any? || block_given?
    block_given? ? block[property] : default[0]
  end

  value = nil

  begin
    value = fetch_property_chain(property)
    return value unless value == KEY_NOT_FOUND
  rescue NoMethodError => e
    warn e if ENV["DEBUG"]
    return fetch_default[]
  end

  fetch_default[]
end

#inspectObject



47
48
49
# File 'lib/property_string.rb', line 47

def inspect
  @object.inspect
end