Class: FancyStruct

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ FancyStruct

Returns a new instance of FancyStruct.



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

def initialize(*args)
  if args.size == 1 && args.first.is_a?(Hash)
    self.set(args.first)
  else
    self.class.attribs.each_with_index { |name, i| self.set_attrib(name, args[i]) if args[i] }
  end
end

Class Method Details

.attribs(*attribs) ⇒ Object

the class



34
35
36
37
38
39
40
41
# File 'lib/fancystruct.rb', line 34

def self.attribs(*attribs)
  @attribs ||= []
  unless attribs.empty?
    self.send :attr_accessor, *attribs
    @attribs += attribs 
  end
  @attribs
end

.create(*attribs, &blk) ⇒ Object

class constuctors



5
6
7
8
9
10
# File 'lib/fancystruct.rb', line 5

def self.create(*attribs, &blk)
  c = Class.new(FancyStruct)
  c.attribs *attribs
  c.class_eval(&blk) if blk
  c
end

.deep_obj(obj) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/fancystruct.rb', line 19

def self.deep_obj(obj)
  case obj
  when Array
    obj.map {|e| FancyStruct.deep_obj(e)}
  when Hash
    FancyStruct.obj( obj.each do |k,v|
      obj[k] = FancyStruct.deep_obj(v)
    end )
  else
    obj
  end
end

.obj(hsh) ⇒ Object

object constructors



14
15
16
17
# File 'lib/fancystruct.rb', line 14

def self.obj(hsh)
  keys, values = hsh.to_a.transpose
  FancyStruct(*keys).new(*values)
end

Instance Method Details

#set(attribs) ⇒ Object



51
52
53
54
# File 'lib/fancystruct.rb', line 51

def set(attribs)
  attribs.each { |name,val| self.set_attrib(name, val) }
  self
end

#set_attrib(name, val) ⇒ Object



56
57
58
# File 'lib/fancystruct.rb', line 56

def set_attrib(name,val)
  self.send(name.to_s+'=', val)
end