Sha256: ce0ab07ddb4085d50e39f66b47f67e158e601163d2cb9f769811e64f2d6fd0a8

Contents?: true

Size: 1.23 KB

Versions: 29

Compression:

Stored size: 1.23 KB

Contents

# encoding: utf-8

module SchemaTools
  class Cleaner

    class << self

      # Clean a hash before a new object is created from it. Can be used in
      # your ruby controllers where new objects are created from a params-hash
      # Directly CHANGES incoming params-hash!
      #
      # @param [String|Symbol] obj_name of the object/schema
      # @param [Hash{String|Symbol=>Mixed}] params properties for the object
      # @param [Hash] opts
      # @options opts [Array<String|Symbol>] :keep properties not being kicked
      # even if defined as readonly
      def clean_params!(obj_name, params, opts={})
        schema = SchemaTools::Reader.read(obj_name)
        setters = []
        # gather allowed properties
        schema[:properties].each{ |k,v| setters << k if !v['readonly'] }
        setters += opts[:keep] if opts[:keep] && opts[:keep].is_a?(Array)
        # kick readonly
        params.delete_if { |k,v| !setters.include?("#{k}")  }
        #convert to type in schema,
        # atm. only strings since number can vary float, int, BigDec
        params.each do |k,v|
          if schema[:properties]["#{k}"]['type'] == 'string' && !v.is_a?(String)
            params[k] = "#{v}"
          end
        end
      end

    end
  end
end

Version data entries

29 entries across 29 versions & 1 rubygems

Version Path
json_schema_tools-0.5.3 lib/schema_tools/cleaner.rb
json_schema_tools-0.5.2 lib/schema_tools/cleaner.rb
json_schema_tools-0.5.1 lib/schema_tools/cleaner.rb
json_schema_tools-0.5.0 lib/schema_tools/cleaner.rb
json_schema_tools-0.4.3 lib/schema_tools/cleaner.rb
json_schema_tools-0.4.2 lib/schema_tools/cleaner.rb
json_schema_tools-0.4.1 lib/schema_tools/cleaner.rb
json_schema_tools-0.4.0 lib/schema_tools/cleaner.rb
json_schema_tools-0.3.3 lib/schema_tools/cleaner.rb
json_schema_tools-0.3.2 lib/schema_tools/cleaner.rb
json_schema_tools-0.3.1 lib/schema_tools/cleaner.rb
json_schema_tools-0.3.0 lib/schema_tools/cleaner.rb
json_schema_tools-0.2.6 lib/schema_tools/cleaner.rb
json_schema_tools-0.2.5 lib/schema_tools/cleaner.rb
json_schema_tools-0.2.4 lib/schema_tools/cleaner.rb
json_schema_tools-0.2.3 lib/schema_tools/cleaner.rb
json_schema_tools-0.2.2 lib/schema_tools/cleaner.rb
json_schema_tools-0.2.1 lib/schema_tools/cleaner.rb
json_schema_tools-0.2.0 lib/schema_tools/cleaner.rb
json_schema_tools-0.1.2 lib/schema_tools/cleaner.rb