Module: RubyExt::OpenConstructor

Defined in:
lib/ruby_ext/more/open_constructor.rb

Instance Method Summary collapse

Instance Method Details

#set(values, list = nil) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ruby_ext/more/open_constructor.rb', line 2

def set values, list = nil
  unless list
    if values.is_a? Hash
      values.each do |k, v|
        self.respond_to "#{k}=", v
      end
    else
      values.instance_variables.each do |name|
        accessor = "#{name[1..name.size]}="
        if self.respond_to? accessor
          self.send accessor, values.instance_variable_get(name)
        end
      end
    end
  else
    if values.is_a? Hash
      values.each do |k, v|
        self.respond_to "#{k}=", v if list.include? k
      end
    else
      values.instance_variables.each do |name|
        accessor = name[1..name.size]
        if list.include?(accessor.to_sym)
          accessor = "#{accessor}="
          if self.respond_to?(accessor)
            self.send accessor, values.instance_variable_get(name)
          end
        end
      end
    end
  end
  return self
end

#set!(values) ⇒ Object



36
37
38
39
40
41
# File 'lib/ruby_ext/more/open_constructor.rb', line 36

def set! values
  values.each do |k, v|
    self.send "#{k}=", v
  end
  return self
end

#to_hashObject



43
44
45
46
47
48
49
# File 'lib/ruby_ext/more/open_constructor.rb', line 43

def to_hash
  hash = {}
  instance_variables.each do |name|
    hash[name[1..name.size].to_sym] = instance_variable_get name
  end
  return hash
end