class CardsManager

Constants

InvalidValue
UnknownAttribute

Attributes

cards_source[R]
query[R]

Public Class Methods

new(query, cards_source) click to toggle source
# File lib/cards_manager.rb, line 11
def initialize(query, cards_source)
  @query = query
  @cards_source = cards_source
end

Public Instance Methods

requested_cards() click to toggle source
# File lib/cards_manager.rb, line 16
def requested_cards
  return cards_source if query.empty?

  group_and_select(query, cards_source)
end

Private Instance Methods

group_and_select(query, cards) click to toggle source
# File lib/cards_manager.rb, line 24
def group_and_select(query, cards)
  attribute = query[0][:attribute]
  unknown_attribute(attribute) unless cards.first.key?(attribute)

  selected_cards = matching_cards(query[0], cards)
  new_query = query[1..]

  return selected_cards if new_query.empty?

  selected_cards.map.with_object({}) do |(attribute_value, card_set), hash|
    hash[attribute_value] = group_and_select(new_query, card_set)
  end
end
invalid_value(cli_value) click to toggle source
# File lib/cards_manager.rb, line 57
def invalid_value(cli_value)
  message = "`#{cli_value}`: Type of provided value doesn't match type of card attribute"
  raise InvalidValue, message
end
match?(cli_value, source_value) click to toggle source
# File lib/cards_manager.rb, line 43
def match?(cli_value, source_value)
  return true if cli_value == Query::Group
  return cli_value == source_value if [cli_value, source_value].all? { |val| val.is_a?(String) }
  return cli_value.to_i == source_value if source_value.is_a?(Numeric)

  cli_value.tally == source_value&.tally
rescue NoMethodError
  invalid_value(cli_value)
end
matching_cards(filter, cards) click to toggle source
# File lib/cards_manager.rb, line 38
def matching_cards(filter, cards)
  cards.group_by { |card| card[filter[:attribute]] }
       .select { |key, _| match?(filter[:value], key) }
end
unknown_attribute(attribute) click to toggle source
# File lib/cards_manager.rb, line 53
def unknown_attribute(attribute)
  raise UnknownAttribute, "`#{attribute}`: Is not an MTG card attribute"
end