Class: DynaStruct::Full

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

Instance Method Summary collapse

Constructor Details

#initialize(args = nil) ⇒ Full

Returns a new instance of Full.



3
4
5
6
7
8
# File 'lib/dyna_struct/full.rb', line 3

def initialize(args=nil)
  args.each_pair do |k, v|
    instance_variable_set("@#{k}", v)
    add_attribute(k)
  end if args.kind_of?(Hash)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_id, *args) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/dyna_struct/full.rb', line 34

def method_missing(method_id, *args)
  method_name = method_id.id2name
  len = args.length
  if method_name.chomp!(?=)
    if len != 1
      raise ArgumentError, "wrong number of arguments (#{len} for 1)", caller(1)
    end
    self[method_name] = args.first
  elsif method_name.chomp!(??)
    unless len.zero?
      raise ArgumentError, "wrong number of arguments (#{len} for 0)", caller(1)
    end
    !!self[method_name]
  elsif len == 0
    self[method_name]
  else
    super
  end
end

Instance Method Details

#[](name) ⇒ Object



10
11
12
# File 'lib/dyna_struct/full.rb', line 10

def [](name)
  instance_variable_get("@#{name}")
end

#[]=(name, value) ⇒ Object



14
15
16
17
18
# File 'lib/dyna_struct/full.rb', line 14

def []=(name, value)
  instance_variable_set("@#{name}", value)
  add_attribute(name)
  value
end

#delete_field(name) ⇒ Object



27
28
29
30
31
32
# File 'lib/dyna_struct/full.rb', line 27

def delete_field(name)
  if respond_to?(name)
    remove_singleton_method(name, "#{name}=")
    remove_instance_variable("@#{name}")
  end
end

#to_hObject Also known as: to_hash



20
21
22
23
24
# File 'lib/dyna_struct/full.rb', line 20

def to_h
  instance_variables.inject({}) do |result, var|
    result.merge var.to_s[1..-1].to_sym => instance_variable_get(var)
  end
end