【问题标题】:What is the best way to emulate `around_filter` when using Grape?使用 Grape 时模拟 `around_filter` 的最佳方法是什么?
【发布时间】:2016-04-18 14:05:13
【问题描述】:

我想为我的应用收到的每个请求设置时区,application_controller.rb 我这样做了:

around_filter :user_time_zone, :if => :current_user

def user_time_zone(&block)
  Time.use_zone(current_user.time_zone, &block)
end

但我很难找到适合我当前使用 Grape gem 的应用程序的等效项。

我唯一找到的似乎是this

use Grape::Middleware::Filter, before: lambda {  Time.zone current_user.time_zone }, after: lambda { Time.zone 'UTC' }

但我想知道是否有更清洁的东西

【问题讨论】:

    标签: ruby-on-rails ruby grape


    【解决方案1】:

    您可以将这种常见行为放在一个模块中。

    这是我做类似事情的方法:

    module API
      module V1
        module Defaults
          extend ActiveSupport::Concern
    
          included do
            helpers do
              def current_user
                # ...
              end
            end
    
            before do
              Time.zone = current_user.timezone
            end
    
            after do
              Time.zone = Rails.configuration.time_zone
            end
          end
        end
      end
    end
    
    module API
      module V1
        class Things < Grape::API
    
          include API::V1::Defaults
    
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2020-02-03
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      相关资源
      最近更新 更多