Module: ServiceStack::DTO
- Included in:
- AuditBase, Authenticate, AuthenticateResponse, ConvertSessionToToken, ConvertSessionToTokenResponse, EmptyResponse, GetAccessToken, GetAccessTokenResponse, IdResponse, QueryBase, QueryResponse, Register, RegisterResponse, ResponseError, ResponseStatus, StringResponse, StringsResponse
- Defined in:
- lib/servicestack/dto.rb
Overview
Included by generated DTOs to convert them to and from the JSON their APIs are serialized with.
Generated DTOs declare the wire name and Type of each property, which is what lets nested DTOs, Dates and collections round-trip correctly:
class Booking
include ServiceStack::DTO
attr_accessor :id, :booking_start_date, :discount
def self.properties
{
id: { name: 'id' },
booking_start_date: { name: 'bookingStartDate', type: DateTime },
discount: { name: 'discount', type: Coupon },
}
end
end
Defined Under Namespace
Modules: ClassMethods, Serializer
Class Method Summary collapse
Instance Method Summary collapse
- #==(other) ⇒ Object
-
#initialize(**kwargs) ⇒ Object
Creates a DTO, populating any properties passed as keyword args, e.g:.
- #inspect ⇒ Object
-
#to_hash ⇒ Object
(also: #to_h)
The DTO as the Hash it's serialized to, using its wire property names and omitting any properties that aren't populated.
-
#to_json(*args) ⇒ Object
The DTO as its JSON representation.
Class Method Details
.included(base) ⇒ Object
25 26 27 |
# File 'lib/servicestack/dto.rb', line 25 def self.included(base) base.extend(ClassMethods) end |
Instance Method Details
#==(other) ⇒ Object
63 64 65 |
# File 'lib/servicestack/dto.rb', line 63 def ==(other) other.is_a?(self.class) && to_hash == other.to_hash end |
#initialize(**kwargs) ⇒ Object
Creates a DTO, populating any properties passed as keyword args, e.g:
Hello.new(name: 'World')
32 33 34 35 36 37 38 39 40 41 |
# File 'lib/servicestack/dto.rb', line 32 def initialize(**kwargs) kwargs.each do |key, value| setter = "#{key}=" unless respond_to?(setter) raise ArgumentError, "unknown property '#{key}' for #{self.class}" end public_send(setter, value) end end |
#inspect ⇒ Object
67 68 69 |
# File 'lib/servicestack/dto.rb', line 67 def inspect "#<#{self.class} #{to_hash.map { |k, v| "#{k}=#{v.inspect}" }.join(', ')}>" end |
#to_hash ⇒ Object Also known as: to_h
The DTO as the Hash it's serialized to, using its wire property names and omitting any properties that aren't populated.
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/servicestack/dto.rb', line 45 def to_hash to = {} self.class.all_properties.each do |attr, | value = instance_variable_get("@#{attr}") next if value.nil? to[[:name] || attr.to_s] = Serializer.to_json_value(value) end to end |
#to_json(*args) ⇒ Object
The DTO as its JSON representation.
58 59 60 61 |
# File 'lib/servicestack/dto.rb', line 58 def to_json(*args) require 'json' to_hash.to_json(*args) end |