Class: BasicSerializer

Inherits:
Object
  • Object
show all
Extended by:
DSL, Swagger
Defined in:
lib/basic_serializer.rb,
lib/basic_serializer/dsl.rb,
lib/basic_serializer/hash.rb,
lib/basic_serializer/config.rb,
lib/basic_serializer/swagger.rb

Defined Under Namespace

Modules: Config, DSL, Swagger Classes: Hash

Constant Summary collapse

Struct =
Class.new(Struct)

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from DSL

attribute, attributes, custom_model_name, format, format_settings, model_name, schema_ref

Methods included from Swagger

swagger_ref, swagger_schema

Constructor Details

#initialize(object) ⇒ BasicSerializer

Returns a new instance of BasicSerializer.



17
18
19
20
21
22
23
# File 'lib/basic_serializer.rb', line 17

def initialize(object)
  @object = object

  @object = @object.is_a?(::Hash) ? struct : @object

  remove_instance_variable(:@struct) if defined?(@struct)
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



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

def object
  @object
end

Instance Method Details

#serializeObject



39
40
41
42
43
44
45
# File 'lib/basic_serializer.rb', line 39

def serialize
  case self.class.format_settings[:name]
  when :json then to_json
  when :yaml then to_yaml
  else stringified_attributes
  end
end

#stringified_attributesObject Also known as: as_json



25
26
27
# File 'lib/basic_serializer.rb', line 25

def stringified_attributes
  hash.deep_stringify_keys
end

#to_json(*_args) ⇒ Object



31
32
33
# File 'lib/basic_serializer.rb', line 31

def to_json(*_args)
  Oj.dump(stringified_attributes, **json_format_options)
end

#to_yamlObject



35
36
37
# File 'lib/basic_serializer.rb', line 35

def to_yaml
  YAML.dump(stringified_attributes)
end