Is it prefer to use attach_workspace for caching gems

Is attach_workspace used for restoring cache? What is the main purpose for?

In the documentation, restore_cache restores gems at working directory not to use attach_workspace. I sometimes see that attach_workspace and persist_to_workspace is used for restoring and caching gems.

build:
  working_directory: ~/app

  steps:
    - checkout

    - restore_cache:
        keys:
          - rails-bundle-v1-{{ checksum "Gemfile.lock" }}
          - rails-bundle-v1-

    - run:
        name: bundle install
        command: bundle check --path vendor/bundle || bundle install --deployment

    - save_cache:
        key: rails-bundle-v1-{{ checksum "Gemfile.lock" }}
        paths:
          - vendor/bundle

    - persist_to_workspace:
        root: ~/app
        paths:
          - vendor/bundle

deploy:
  working_directory: ~/app

  steps:
    - checkout

    - attach_workspace: # <- Is it possible to restore cache????
        at: ~/app

I also tried restoring gems without persist_to_workspace and attach_workspace. Please refer .circleci/config.yml and its results form following links. It has finished successfully!

:wave: The core difference between workspaces and caching is that workspaces are scoped to your workflow whereas caches are available across all workflows in your project.

Workflows are useful for passing artefacts between jobs in a single workflow. For example, say you have some build artefacts from the first job in your workflow and you want to use these in a subsequent job, you would save them to the workspace in the first job, then attach the workspace in the next job to retrieve them. Once the workflow has finished, the workspace is no longer accessible and therefore you will not be able to retrieve anything you saved there on the next build you trigger.

Caching allows you to save a cache and then retrieve it in any subsequent job, even if it is not part of the same workflow, as long as you use the same cache key.

In this case of Ruby Gems, it would be best to use caching as you would want to restore those Gems in every subsequent job, even on builds triggered by new commits.

An example of caching Ruby Gems can be found in our documentation:

I hope this clarifies the difference between workspaces and caching!