Class: DTO

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

Overview

DTO class allows to create a structure that support export to json and construct with a hash.

Example of use:

class User < DTO.new(:first_name, :last_name, :birthday)

end

or

User = Class.new(DTO.new :first_name, :last_name, :birthday)

Instance Method Summary collapse

Constructor Details

#initialize(attrs = {}) ⇒ DTO

Returns a new instance of DTO.



16
17
18
19
20
# File 'lib/dto.rb', line 16

def initialize(attrs = {})
  members.each do |member|
    send("#{member}=", attrs[member])
  end
end

Instance Method Details

#to_jsonObject



22
23
24
25
26
# File 'lib/dto.rb', line 22

def to_json
  attrs = {}
  members.each { |attr| attrs[attr] = send(attr) }
  attrs.to_json
end

#to_sObject



28
29
30
# File 'lib/dto.rb', line 28

def to_s
  members.map { |attr| "#{attr}: #{send(attr)}" }.join(", ")
end