Sha256: 230c7cb6649f524f2feae360ecb0a546bc3d9c0bc3635cbb4318defedcca0c89

Contents?: true

Size: 1.36 KB

Versions: 7

Compression:

Stored size: 1.36 KB

Contents

require 'voom/parameters'
require 'voom/trace'

module Voom
  # Simple serializer that will build add a to_hash method to an object by inspecting
  # the intersection of its instance variables and public accessor methods.
  module Serializer
    include Trace

    def to_hash(serializer=true)
      trace {self.class.to_s}
      return build_hash unless serializer
      begin
        serializer_name = "#{self.class.to_s}Serializer"
        serializer = Module.const_get(serializer_name)
        serializer.new(self).to_hash
      rescue NameError
        build_hash
      end
    end

    private
    def build_hash
      accessable = instance_variables.map {|i| i.to_s.gsub('@', '').to_sym} & methods
      accessable.reduce({}) do |hash, v|
        trace {"#{v}:#{params.inspect}"}
        params = Parameters.new(method(v).parameters)
        unless params.required_args? || params.required_options?
          value = self.send(v)
          value = if value.kind_of?(Array)
                    value.map {|v_| v_.respond_to?(:to_hash) ? v_.to_hash : v_}
                  elsif value.kind_of?(Hash)
                    value.map {|k, v_| v_.respond_to?(:to_hash) ? [k, v_.to_hash] : [k, v_]}.to_h
                  else
                    value.respond_to?(:to_hash) ? value.to_hash : value
                  end
          hash[v]= value
        end
        hash
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
voom-presenters-2.1.2 lib/voom/serializer.rb
voom-presenters-2.1.0 lib/voom/serializer.rb
voom-presenters-2.0.3 lib/voom/serializer.rb
voom-presenters-2.0.2 lib/voom/serializer.rb
voom-presenters-2.0.1 lib/voom/serializer.rb
voom-presenters-2.0.0 lib/voom/serializer.rb
voom-presenters-0.2.0 lib/voom/serializer.rb