Sha256: d5c49a8086f5b097294c16cf5adfed45dcf94eec28db7bd630deb66ace03a6c6

Contents?: true

Size: 1.37 KB

Versions: 12

Compression:

Stored size: 1.37 KB

Contents

require 'coprl/parameters'
require 'coprl/trace'

module Coprl
  # 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

12 entries across 12 versions & 1 rubygems

Version Path
coprl-3.0.0.beta.12 lib/coprl/serializer.rb
coprl-3.0.0.beta.11 lib/coprl/serializer.rb
coprl-3.0.0.beta.10 lib/coprl/serializer.rb
coprl-3.0.0.beta.9 lib/coprl/serializer.rb
coprl-3.0.0.beta.8 lib/coprl/serializer.rb
coprl-3.0.0.beta.7 lib/coprl/serializer.rb
coprl-3.0.0.beta.6 lib/coprl/serializer.rb
coprl-3.0.0.beta.5 lib/coprl/serializer.rb
coprl-3.0.0.beta.4 lib/coprl/serializer.rb
coprl-3.0.0.beta.3 lib/coprl/serializer.rb
coprl-3.0.0.beta.2 lib/coprl/serializer.rb
coprl-3.0.0.beta.1 lib/coprl/serializer.rb