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

【Sinatra】オートロード && オートリロードしてほしい

More than 3 years have passed since last update.

http://qiita.com/izumin5210/items/cd2f9f48fbe1fdcaf628 の続編

sinatra-reloaderを使わなければもっと楽になる気がする…


導入

とりあえずsinatra-contribと`activesupport'を入れる.

Gemfile
# 前略

gem 'sinatra'
gem 'sinatra-contrib'
gem 'activesupport'

# 後略

ディレクトリ構成例

config/boot.rbを用意し,最初にこれを読ませるようにする.

.
├── Gemfile
├── Gemfile.lock
├── config
│   ├── boot.rb
│   ├── database.yml
│   └── global
├── config.ru
├── lib
│   ├── app
│   ├── models
│   ├── ...
│
...

オートロードにActiveSupport::Dependenciesを利用するので,ファイル名とその中に定義されてるmodule/class名はその規約に従わないといけない.

e.g.

  • ./lib/models/user.rb => User
  • ./lib/models/app/user.rb => App::User

有効化

Classic Application

オートロード

ActiveSupport::Dependencies.autoload_pathsに対象ディレクトリ(ここでは./lib以下の各ディレクトリ)を喰わせる.

config/boot.rb
ROOT_DIR = File.join(File.expand_path(File.dirname(__FILE__)), '..')
SOURCES_DIR = File.join(ROOT_DIR, 'lib')
ActiveSupport::Dependencies.autoload_paths = Dir[File.join(SOURCES_DIR, '**')]

オートリロード

どこかでsinatra/reloaderを有効化する.その後,オートリロードしたいファイル(ここでは./lib以下の各*.rbファイル)をalso_reloadに喰わせる.

lib/app/app.rb
require 'sinatra'

if development?
  require 'sinatra/reloader'
  Dir[File.join(SOURCES_DIR, '**', '*.rb')].each { |f| also_reload f }
end

Modular Application

オートロード

Classicのときと同じ.

オートリロード

だいたい似たような感じ.

app.rb
require 'sinatra/reloader' if development?

class App < Sinatra::Base
  configure :development do
    register Sinatra::Reloader
    Dir[File.join(SOURCES_DIR, '**', '*.rb')].each { |f| also_reload f }
  end

  # snip.
end

参考

izumin5210
ʕ ◔ϖ◔ʔ < I'm a Rubyist.
https://blog.izum.in
wantedly
「シゴトでココロオドル」ためのビジネスSNS「Wantedly」の開発・運営をしています。
https://wantedlyinc.com/ja/presentations
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
ユーザーは見つかりませんでした