1

親アプリケーションのユーザーモデルとの関係を確立するために「動作」形式を使用するRailsエンジンを構築しています。

module Cornerstone

  module ActsAsCornerstoneUser

    extend ActiveSupport::Concern

    module ClassMethods

      def acts_as_cornerstone_user(options = {})

        #= Associations
        has_many :cornerstone_discussions


        #= Options
        Cornerstone::Config.auth_with << options[:auth_with] if options[:auth_with]
        Cornerstone::Config.auth_with.flatten!

      end
    end

    module InstanceMethods

    end

  end

  ActiveRecord::Base.send :include, ActsAsCornerstoneUser

end

開発者がオプションを使用してヘルパーメソッド名を指定できるようにしたいと思い:auth_withます。開発者は、親アプリケーションで、そのセッションのサインインしたユーザーを返すヘルパーメソッドを指定するという考え方です。

私の質問は、開発者がauth_withオプションを指定したら、その親アプリケーションのメソッドをどのように呼び出すことができますか?

親アプリケーションのサインインしたユーザーを取得するためのより良いアプローチはありますか?単に呼び出すことに依存しないように、できるだけ柔軟にしたいと思いcurrent_userます。

4

1 に答える 1

2

アプリケーションで定義されている基礎となるユーザーが1人だけである限り、このようなものが機能するはずです。

module Cornerstone
  module ActsAsCornerstoneUser
    extend ActiveSupport::Concern

    module ClassMethods
      def acts_as_cornerstone_user(options = {})

        #= Associations
        has_many :cornerstone_discussions

        #= Options
        Cornerstone::Config.auth_with = options[:auth_with] if options[:auth_with]
      end
    end

    module InstanceMethods

    end

    def self.included(base)
      base.extend(ClassMethods)
      base.include(InstanceMethods)
    end
  end

  ActiveRecord::Base.send :include, ActsAsCornerstoneUser
end

次に、gemでヘルパーを定義します(つまり、でapp/helpers/cornerstone_helper.rb):

module Cornerstone
  module CornerStoneHelper
    def current_cornerstone_user
      Config.auth_with.call(controller)
    end
  end
end

acts_as_cornerstoneメソッドは次のように使用されます:

class MyUser < ActiveRecord::Base
  acts_as_cornerstone_user :auth_with => Proc.new { |controller| controller.current_user }
end

次に、current_cornerstone_userヘルパーを使用して、現在認証されているユーザーを取得できます。

このメソッドはacts_as_cornerstone_user、複数のクラスで使用されると機能しなくなります。しかし、アプリケーションモデルについて何も知らずに、複数の基礎となるユーザーがいるという問題があります(あなたは自分の宝石の中にいるはずです)。

アップデート

のような構文が必要な:auth_with => :warden場合は、ヘルパーを次のように置き換えることができます。

module Cornerstone
  module CornerStoneHelper
    def current_cornerstone_user
      if Config.auth_with.respond_to?(:call)
        Config.auth_with.call(controller)
      elsif Config::AUTH_MODES.keys.include?(Config.auth_with)
        Config::AUTH_MODES[Config.auth_with].call(controller)
      end
    end
  end
end

このようにCornerstone::Config::AUTH_MODES設定すると:

module Cornerstone
  class Config
    AUTH_MODES = {
      :warden => Proc.new { |controller| controller.env['warden'].user },
      :devise => Proc.new { |controller| controller.current_user }
    }
  end
end
于 2011-08-07T16:05:57.600 に答える