Module: StructTrans

Defined in:
lib/struct_trans.rb,
lib/struct_trans/hash.rb,
lib/struct_trans/ostruct.rb

Class Method Summary collapse

Class Method Details

.construct_hashObject



11
12
13
# File 'lib/struct_trans/hash.rb', line 11

def construct_hash
  {}
end

.construct_ostructObject



11
12
13
# File 'lib/struct_trans/ostruct.rb', line 11

def construct_ostruct
  OpenStruct.new
end

.trans_hash(struct, schema) ⇒ Object



7
8
9
# File 'lib/struct_trans/hash.rb', line 7

def trans_hash struct, schema
  transform(:hash, struct, schema)
end

.trans_ostruct(struct, schema) ⇒ Object



7
8
9
# File 'lib/struct_trans/ostruct.rb', line 7

def trans_ostruct struct, schema
  transform(:ostruct, struct, schema)
end

.transform(kind, struct, schema) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/struct_trans.rb', line 7

def transform kind, struct, schema
  case schema
  when Symbol
    struct.public_send(schema)
  when Array
    schema.map do |key|
      transform(kind, struct, key)
    end
  when Hash
    schema.inject(public_send("construct_#{kind}")) do |box, (key, value)|
      public_send("write_#{kind}",
        box, key, transform(kind, struct.public_send(key), value))
      box
    end
  else
    raise TypeError.new("Unknown type: #{schema.class}: #{schema}")
  end
end

.write_hash(hash, key, value) ⇒ Object



15
16
17
# File 'lib/struct_trans/hash.rb', line 15

def write_hash hash, key, value
  hash[key] = value
end

.write_ostruct(ostruct, key, value) ⇒ Object



15
16
17
# File 'lib/struct_trans/ostruct.rb', line 15

def write_ostruct ostruct, key, value
  ostruct.public_send("#{key}=", value)
end