6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RubyプロジェクトのgemをBundlerで管理

Posted at

業務でMechanizeを使ったスクレイピングをする機会があり、RubyプロジェクトをBundlerで管理する手順を共有します。
Bundlerを使ってgemを管理するメリットは以下参照
https://blog.tokoyax.com/entry/ruby/bundler

Bundlerをインストール

$ gem install bundler

Bundlerをグローバルインストールします。

Rubyプロジェクトを作成する

$ mkdir ruby_project
$ cd ruby_project

Rubyプロジェクトを作成するためのフォルダを作成して、移動します。

Bundler を使った gem のローカルインストール

$ bundle init

これで、プロジェクトのルートにGemfileが作成されます。

source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

# gem "rails"

# 以下のgemを追加
gem 'mechanize'

作成されたGemfileにgem 'mechanize'の記述を追加します。

$ bundle install --path=vendor/bundle

Bundler で Gemfile に書かれている gem をインストールします。
新たにGemfile.lockが作成されて、その中にインストールされたgem一覧が記述されています。
これで、gemのローカルインストールが完了しました。

gemがローカルインストールされているか確認

gemがグローバルインストールされているか、ローカルインストールされているかは以下の方法で検証できます。

$ gem list | grep mechanize              # グローバルインストールされているgem一覧
$ bundle exec gem list | grep mechanize  # ローカルインストールされているgem一覧
mechanize (2.7.6)

bundle execを付けた方だけ、mechanize (2.7.6)が表示されているのでローカルでのみ
mechanizeのインストールが完了しています。

スクレイピングするRubyコードの作成

最後に、Rubyコードを書いていきます。

mkdir scraper
vi scraping.rb

Rubyファイルを編集します。

scraping.rb
require 'mechanize'

agent = Mechanize.new
page = agent.get("http://qiita.com")
elements = page.search('title')
puts elements
実行コマンド
bundle exec ruby scraper/scraping.rb
実行結果
<title>Qiita</title>
<title>Qiita</title>

補足

ちなみに、bundle execを実行コマンドの前につけることでローカルのgemが適用されます。
bundle execを実行コマンドの前に付けなかった場合、グローバルのgemが適用され、グローバルgemにはmechanizeをインストールしていないためエラーになります。

実行コマンド
ruby scraper/scraping.rb
実行結果
/Users/tatsuminaoki/.rbenv/versions/2.4.1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- mechanize (LoadError)
	from /Users/tatsuminaoki/.rbenv/versions/2.4.1/lib/ruby/2.4.0/rubygems/core_ext/kernel_require.rb:55:in `require'
	from scraper/mansion_review.rb:1:in `<main>'

これで、RubyプロジェクトをBundlerで管理することができました。

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?