Sha256: 18e226c9a3d9c359b15d1f405958bfa24d3168dc34c3ddc48767200c61e173ce

Contents?: true

Size: 1.37 KB

Versions: 14

Compression:

Stored size: 1.37 KB

Contents

require_relative 'parameters'
require_relative '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

14 entries across 14 versions & 1 rubygems

Version Path
voom-presenters-0.1.13 lib/voom/serializer.rb
voom-presenters-0.1.12 lib/voom/serializer.rb
voom-presenters-0.1.11 lib/voom/serializer.rb
voom-presenters-0.1.10 lib/voom/serializer.rb
voom-presenters-0.1.9 lib/voom/serializer.rb
voom-presenters-0.1.8 lib/voom/serializer.rb
voom-presenters-0.1.7 lib/voom/serializer.rb
voom-presenters-0.1.6 lib/voom/serializer.rb
voom-presenters-0.1.5 lib/voom/serializer.rb
voom-presenters-0.1.4 lib/voom/serializer.rb
voom-presenters-0.1.3 lib/voom/serializer.rb
voom-presenters-0.1.2 lib/voom/serializer.rb
voom-presenters-0.1.1 lib/voom/serializer.rb
voom-presenters-0.1.0 lib/voom/serializer.rb