Class: RenderWithView::HalfOpenStruct

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

Overview

Like OpenStruct but doesn’t let you read a non-assigned value (raises instead of returning nil). This avoids issues where you read the wrong value due to a typo and don’t notice.

Borrowed from @henrik, gist.github.com/henrik/19c68b2a41ab4d098ce8

Direct Known Subclasses

View

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}) ⇒ HalfOpenStruct

Returns a new instance of HalfOpenStruct.



10
11
12
# File 'lib/render_with_view/half_open_struct.rb', line 10

def initialize(hash = {})
  @hash = hash
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



22
23
24
25
26
27
28
29
30
# File 'lib/render_with_view/half_open_struct.rb', line 22

def method_missing(name, *args)
  if name.to_s.end_with?("=")
    write(name.to_s.chop.to_sym, *args)
  elsif args.length == 0
    read_or_raise(name)
  else
    raise NoMethodError
  end
end

Instance Method Details

#fetch(name, fallback) ⇒ Object



18
19
20
# File 'lib/render_with_view/half_open_struct.rb', line 18

def fetch(name, fallback)
  @hash.fetch(name, fallback)
end

#include?(name) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/render_with_view/half_open_struct.rb', line 14

def include?(name)
  @hash.include?(name)
end