メインのSinatra project_name.rbにヘルパーがたくさんあります。それらを外部ファイルに削除したいのですが、それを実行するベストプラクティスは何ですか? exapmple ./helpers/something.rb外部ファイル内のsinatraヘルパー
ため./preject_name.rb
helpers do
...#bunch of helpers
end
から
には、あなたがそれを言ったのと同じようにあなた自身を
メインのSinatra project_name.rbにヘルパーがたくさんあります。それらを外部ファイルに削除したいのですが、それを実行するベストプラクティスは何ですか? exapmple ./helpers/something.rb外部ファイル内のsinatraヘルパー
ため./preject_name.rb
helpers do
...#bunch of helpers
end
から
には、あなたがそれを言ったのと同じようにあなた自身を
に感謝:
helpers
ブロックを別のファイルに移動し、必要な場所はです。 、私のように、あなたはモジュラーシナトラアプリを構築している場合
#helpers.rb
helpers do
...
end
#project_name.rb
require 'path/to/helpers.rb'
ああは、それは少し複雑単に別のファイルに出helpers
を移動するよりもです。
私がこれを動作させる唯一の方法は次のとおりです。
最初にあなたのアプリで(私はこのmy_modular_app.rb
を呼ぶことにします)
require 'sinatra/base'
require 'sinatra/some_helpers'
class MyModularApp < Sinatra::Base
helpers Sinatra::SomeHelpers
...
end
、その後、フォルダ構造./lib/sinatra/
を作成し、次のようにsome_helpers.rb
を作成します。
require 'sinatra/base'
module Sinatra
module SomeHelpers
def help_me_world
logger.debug "hello from a helper"
end
end
helpers SomeHelpers
end
あなたは、単に分割することができ、これを行いますすべてのヘルパーを複数のファイルにまとめることができ、大規模なプロジェクトではより明確になります。
もっとシンプルにできると思います。以下の回答を参照してください。 – kgpdeveloper
シンプルで推奨される方法は:
module ApplicationHelper
# methods
end
class Main < Sinatra::Base
helpers ApplicationHelper
end
私はそれに行くよ –
@DaveSag素晴らしい。 Sinatraの本を読んだら、それがそこにあります。 – kgpdeveloper
これは受け入れられる回答である必要があります – Jonah
答えがミスに何かを提供し@DaveSagようです。 my_modular_app.rb
の先頭に行を追加する必要があります:誰かが私のような「古典的なスタイル」を好む場合は、さらに
$:.unshift File.expand_path('../lib', __FILE__) # add ./lib to $LOAD_PATH
require 'sinatra/base'
require 'sinatra/some_helpers' # this line breaks unless line 1 is added.
# more code below...
、次はあなたのためです:)
app.rb でのlib /シナトラ/ some_helpers.rbで$:.unshift File.expand_path('../lib', __FILE__)
require 'sinatra'
require 'sinatra/some_helpers'
get '/' do
hello_world
end
module Sinatra
module SomeHelper
def hello_world
"Hello World from Helper!!"
end
end
helpers SomeHelper
end
lol、単純:)私は最初にtryiedしなかった理由:)ありがとう、私は使用しています#{File.dirname(__ FILE __)}/helpers/helpers.rb " – equivalent8
Ruby 1.9を使用すると.2あなたは 'require_relative 'helpers/helpers''を' File'-constructの代わりに使用するかもしれません – daddz
何が利点ですか? ...と私はちょっとこのプロジェクトをすべてのマシン上で実行したいと思っています。共有のためにgithub上にあるでしょう:) – equivalent8