Sha256: 0bd61a630dd2dbad7a11d4382daa770caea39edbb58442330f41212f3a8f9855

Contents?: true

Size: 1.92 KB

Versions: 22

Compression:

Stored size: 1.92 KB

Contents

class Card
  # Card::Mark provides class methods for Card to translate all different kind
  # of card identifiers to card objects.
  module Mark
    ID_MARK_RE = /^~(?<id>\d+)$/.freeze
    CODENAME_MARK_RE = /^:(?<codename>\w+)$/.freeze

    # translates marks (and other inputs) into a Card
    #
    # @param cardish [Card, Card::Name, String, Symbol, Integer]
    # @return Card
    def cardish cardish
      if cardish.is_a? Card
        cardish
      else
        fetch cardish, new: {}
      end
    end

    # translates various inputs into either an id or a name.
    # @param parts [Array<Symbol, Integer, String, Card::Name, Card>] a mark or mark parts
    # @return [Integer or Card::Name]
    def id_or_name parts
      mark = parts.flatten
      mark = mark.first if mark.size <= 1
      id_from_mark(mark) || Card::Name[mark]
    end

    # translates string identifiers into an id:
    #   - string id notation (eg "~75")
    #   - string codename notation (eg ":options")
    #
    # @param mark [String]
    # @return [Integer or nil]
    def id_from_string mark
      case mark
      when ID_MARK_RE       then Regexp.last_match[:id].to_i
      when CODENAME_MARK_RE then Card::Codename.id! Regexp.last_match[:codename]
      end
    end

    def name_from_id_from_string id, string
      fetch_name(id) { bad_mark string }
    end

    private

    def bad_mark string
      case string
      when ID_MARK_RE
        raise Card::Error::NotFound, "id doesn't exist: #{Regexp.last_match[:id]}"
      when CODENAME_MARK_RE
        raise Card::Error::CodenameNotFound,
              "codename doesn't exist: #{Regexp.last_match[:codename]}"
      else
        raise Card::Error, "invalid mark: #{string}"
      end
    end

    def id_from_mark mark
      case mark
      when Integer then mark
      when Symbol  then Card::Codename.id! mark
      when String  then id_from_string mark
      when Card    then mark.id
      end
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
card-1.107.0 lib/card/mark.rb
card-1.106.0 lib/card/mark.rb
card-1.105.6 lib/card/mark.rb
card-1.105.5 lib/card/mark.rb
card-1.105.4 lib/card/mark.rb
card-1.105.3 lib/card/mark.rb
card-1.105.2.pre1 lib/card/mark.rb
card-1.105.2 lib/card/mark.rb
card-1.105.1 lib/card/mark.rb
card-1.105.0 lib/card/mark.rb
card-1.104.2 lib/card/mark.rb
card-1.104.1 lib/card/mark.rb
card-1.104.0 lib/card/mark.rb
card-1.103.4 lib/card/mark.rb
card-1.103.3 lib/card/mark.rb
card-1.103.2 lib/card/mark.rb
card-1.103.1 lib/card/mark.rb
card-1.103.0 lib/card/mark.rb
card-1.101.7 lib/card/mark.rb
card-1.102.0 lib/card/mark.rb