Sha256: 3e8cd2cd07636b7125a71e9763c19e15534951eeb168526baa370fb994604425

Contents?: true

Size: 1.35 KB

Versions: 7

Compression:

Stored size: 1.35 KB

Contents

require 'forwardable'

module Parliament
  class Response
    include Enumerable
    extend Forwardable
    attr_reader :nodes
    def_delegators :@nodes, :size, :each, :select, :map, :select!, :map!, :count, :length, :[], :empty?

    def initialize(nodes)
      @nodes = nodes
    end

    def filter(*types)
      filtered_objects = Array.new(types.size) { [] }

      unless types.empty?
        @nodes.each do |node|
          type_index = types.index(node.type)
          filtered_objects[type_index] << node unless type_index.nil?
        end
      end

      result = build_responses(filtered_objects)

      types.size == 1 ? result.first : result
    end

    def build_responses(filtered_objects)
      result = []

      filtered_objects.each do |objects|
        result << Parliament::Response.new(objects)
      end
      result
    end

    def sort_by(*parameters)
      rejected = []
      grom_nodes = @nodes.dup
      grom_nodes.delete_if { |node| rejected << node unless parameters.all? { |param| node.respond_to?(param) } }
      grom_nodes.sort_by! do |node|
        parameters.map do |param|
          node.send(param).is_a?(String) ? I18n.transliterate(node.send(param)).downcase : node.send(param)
        end
      end

      rejected.concat(grom_nodes)
    end

    def reverse_sort_by(*parameters)
      sort_by(*parameters).reverse!
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
parliament-ruby-0.5.17 lib/parliament/response.rb
parliament-ruby-0.5.16 lib/parliament/response.rb
parliament-ruby-0.5.15 lib/parliament/response.rb
parliament-ruby-0.5.14 lib/parliament/response.rb
parliament-ruby-0.5.13 lib/parliament/response.rb
parliament-ruby-0.5.12 lib/parliament/response.rb
parliament-ruby-0.5.8 lib/parliament/response.rb