3

Trailblazer を使用して Rails4 アプリを構築しています。これまで Trailblazer を使用したことがなく、どうすればよいか戸惑っています。

オークションサイトを構築中です。以前は従来のコントローラーを使用していましたが、このルート エンドポイントは正常に機能していました。

 def bill    
     @profile = Profile.find_by user_id: current_user_id
     @current_order = Order.order(created_at: :desc).find_by(user_id: current_user_id)
     @batch = @current_order.batch

     if @batch.nil?
       puts "There was no batch linked to the current order of #{@current_order.id}"
       flash[:error] = "We are sorry, but we could not determine which batch your order belongs to."
     else
       @price_shown_to_customer = @batch.price + ENV["FUELBID_FEE_PER_GALLON"].to_f
       @amount = @current_order.quantity * @price_shown_to_customer
     end

しかし、ここでは、Representer クラスを使用して、これを Trailblazer API として作成することを想定しています。

したがって、routes.rb に「料金」を追加しました。

 namespace :api do
   get '/price' => 'info#info'
   post '/order' => 'orders#create'
   get '/charges' => 'charges#bill'
 end

この Api を作成しましたが、別の API をコピーして貼り付けました。

 module Api
   class ChargesController < ApiApplicationController

     respond_to :json

     def bill
       respond_with OpenStruct.new.extend(ChargesRepresenter)
     end

   end
 end

上記を単純なリプレゼンターでテストしたところ、すべて正常に機能したため、この時点まではすべて問題ありません。Representer から単純なデータを返すと、次のように問題なく表示されます。

http://localhost:3000/api/charges.json

しかし、current_user を取得する必要があります。これはどのように行われますか?現在、これは機能しません:

 module ChargesRepresenter
   include Roar::JSON

   collection :price_shown_to_customer

   def price_shown_to_customer
     current_order = Order.order(created_at: :desc).find_by(user_id: current_user_id)
     puts "current_order"
     puts current_order.id
     batch = current_order.batch
     batch.price + ENV["FUELBID_FEE_PER_GALLON"].to_f  
   end
 end     

Devise をセットアップし、従来のコントローラーがそれを継承するため、 current_user_id は私の従来のコントローラーに存在します。

  class ChargesController < SecuredController

しかし、Trailblazer Representer でそれを取得する方法はありますか?

4

1 に答える 1

1

この答えが遅すぎないことを願っています。

  1. Module の代わりに Decorator パターンに切り替えることができる場合。
  2. Representer は、コントローラー、コンソール、またはテストから呼び出されたかどうかを知る必要はなく、気にしません。必要なのは、json オブジェクトを構築するためのハッシュだけです。したがって、 current_user_id という別の属性を Representer に渡すだけで、r presenter 内で使用できます。

ご参考までに:

より迅速な回答が必要な場合は、質問をhttps://gitter.im/trailblazer/chatにコピーすることもできます。通常、そこには数人の人々がぶらぶらしています。しかし、後世のためにここに質問を投稿することも良いことです。

于 2015-11-29T21:28:45.633 に答える