Help us understand the problem. What is going on with this article?

did_you_mean を使って key の名前を間違っても頑張ってアクセスできる Hash にする

More than 1 year has passed since last update.

did_you_mean 1.2.0 から KeyError に対して key の予測候補が出せるようになったので、これを使って key を間違ってもアクセス出来るようにします。

https://github.com/yuki24/did_you_mean/blob/master/CHANGELOG.md#new-features

key の候補を取得するのには DidYouMean::KeyErrorChecker を使用します。

Hash.prepend Module.new {
  def [](key)
    fetch(key)
  rescue KeyError => ex
    orig_key = key
    key = DidYouMean::KeyErrorChecker.new(ex).corrections.first

    return super(orig_key) if key.nil?

    if key.start_with?(':')
      super(key[1..-1].to_sym)
    else
      super(key)
    end
  end
}

hash = { 
  user: {
    name: 'foo'
  }
}

p hash[:usre][:namee] #=> "foo"

まず [] メソッドはそのままでは key が存在しない場合にエラーが出ないので fetch を使用するように書き換えておきます。その後、KeyError の例外をキャッチして候補を探し出し、候補が存在していればその値を存在しない場合は nil を返すようにしています。

これで key を間違ってもある程度アクセス可能な Hash にすることが出来ました :wrench:

関連記事

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした