Class: DynamicClass

Inherits:
Object show all
Defined in:
lib/common/dynamic_class.rb

Overview

o = DynamicClass.new name: ‘a’ o.name -> ‘a’ o.name = ‘b’ o.name ‘b’ o.name -> ‘b’ o.name = nil o.name -> nil o.title -> raises error

Instance Method Summary collapse

Constructor Details

#initialize(data, &block) ⇒ DynamicClass

Returns a new instance of DynamicClass.



10
11
12
13
# File 'lib/common/dynamic_class.rb', line 10

def initialize data, &block
  @data  = data
  @block = block if block
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, arg = :_UNDEF) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/common/dynamic_class.rb', line 15

def method_missing m, arg=:_UNDEF
  key = m.to_s.sub('=','').to_sym

  unless @data.has_key?(key)
    raise ArgumentError.new('Key :%s not found in DynamicOptions' % key)
  end

  if arg == :_UNDEF
    @data[key]
  else
    @data[key] = arg
  end
end