Module: AttrHelper::Serialization

Included in:
DataPackage::Base
Defined in:
lib/attr_helper/serialization.rb

Instance Method Summary collapse

Instance Method Details

#to_hashObject



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/attr_helper/serialization.rb', line 5

def to_hash
  {}.tap do |hsh|
    attributes.each do |attribute|
      next unless attribute.serializable?
      
      value = attribute.serialized(self)

      if value.respond_to?(:empty?)
        hsh[attribute.key] = value unless value.empty?
      else
        hsh[attribute.key] = value unless value.nil?
      end
    end
  end
end

#to_json(options = {}) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/attr_helper/serialization.rb', line 21

def to_json(options = {})
  if options[:pretty].nil? || options[:pretty]
    JSON.pretty_generate(to_hash)
  else
    JSON.generate(to_hash)
  end
end