Ответ 1
Вот суть который показывает, как получить доступ к классу подкласса и сохранить его в переменной экземпляра и получить доступ к нему в фильтрах до и после. Он использует метод include.
Мне показалось, что я придумал простой способ расширить ApplicationController в Rails 3.x.
В моем драгоценном камне lib/my_namespace/my_controller.rb
у меня было:
class MyNamespace::MyController < ApplicationController
before_filter :some_method
after_filter :another_method
def initialize
# getting classname of the subclass to use for lookup of the associated model, etc.
# and storing the model_class in an instance variable
# ...
end
# define :some_method, :another_method, etc.
# ...
private
attr_accessor :subclass_defined_during_initialize # etc.
# etc.
end
но когда Gem загружен, app/controllers/application_controller.rb
еще не загружен, поэтому он терпит неудачу:
/path/to/rvm/gemset/gems/activesupport-3.2.6/lib/active_support/dependencies.rb:251:
in `require': cannot load such file -- my_gem_name/application_controller (LoadError)
В качестве обходного решения я определил ApplicationController в своем gem lib/gem_namespace/application_controller.rb
как:
class ApplicationController < ActionController::Base
end
Я предположил, что, хотя я и определил его там, он будет переопределен в моем приложении Rails 3 app/controllers/application_controller.rb
, так что оба контроллера в приложении, которые расширили ApplicationController
и контроллеры, которые расширили MyNamespace::MyController
, прямо или косвенно расширьте ApplicationController, определенный в app/controllers/application_controller.rb
.
Однако мы заметили, что после загрузки gem контроллеры, которые расширяют ApplicationController
, не смогли получить доступ к методам, определенным в app/controllers/application_controller.rb
. Кроме того, модуль ApplicationHelper
(app/helpers/application_helper.rb)
больше не загружался другими вспомогательными модулями.
Как я могу расширить ApplicationController
внутри контроллера в моем камне с целью определения before_filter
и after_filter
to и использовать initialize
для доступа к имени класса, чтобы определить связанный с ним класс модели, который он мог бы затем хранить и использовать в своих методах?
Обновление 2012/10/22:
Вот что я придумал:
В lib/your_gem_name/railtie.rb
:
module YourGemsModuleName
class Railtie < Rails::Railtie
initializer "your_gem_name.action_controller" do
ActiveSupport.on_load(:action_controller) do
puts "Extending #{self} with YourGemsModuleName::Controller"
# ActionController::Base gets a method that allows controllers to include the new behavior
include YourGemsModuleName::Controller # ActiveSupport::Concern
end
end
end
и в lib/your_gem_name/controller.rb
:
module YourGemsModuleName
module Controller
extend ActiveSupport::Concern
# note: don't specify included or ClassMethods if unused
included do
# anything you would want to do in every controller, for example: add a class attribute
class_attribute :class_attribute_available_on_every_controller, instance_writer: false
end
module ClassMethods
# notice: no self.method_name here, because this is being extended because ActiveSupport::Concern was extended
def make_this_controller_fantastic
before_filter :some_instance_method_available_on_every_controller # to be available on every controller
after_filter :another_instance_method_available_on_every_controller # to be available on every controller
include FantasticStuff
end
end
# instance methods to go on every controller go here
def some_instance_method_available_on_every_controller
puts "a method available on every controller!"
end
def another_instance_method_available_on_every_controller
puts "another method available on every controller!"
end
module FantasticStuff
extend ActiveSupport::Concern
# note: don't specify included or ClassMethods if unused
included do
class_attribute :class_attribute_only_available_on_fantastic_controllers, instance_writer: false
end
module ClassMethods
# class methods available only if make_this_controller_fantastic is specified in the controller
def some_fanastic_class_method
put "a fantastic class method!"
end
end
# instance methods available only if make_this_controller_fantastic is specified in the controller
def some_fantastic_instance_method
puts "a fantastic instance method!"
end
def another_fantastic_instance_method
puts "another fantastic instance method!"
end
end
end
end
Вот суть который показывает, как получить доступ к классу подкласса и сохранить его в переменной экземпляра и получить доступ к нему в фильтрах до и после. Он использует метод include.
Для этой специфической функциональности я бы рекомендовал создать модуль в вашем камне и включить этот модуль в ваш Application Controller
class ApplicationController < ActionController::Base
include MyCoolModule
end
Чтобы добавить до фильтров и т.д. (добавьте это в свой модуль)
def self.included(base)
base.send(:before_filter, my_method)
end
Обновление: вы можете просто сделать base.before_filter :my_method
, который является более чистым.
Правда намного проще и гибче.
Добавьте к lib/engine.rb
это: class Engine < Rails::Engine; end
А затем просто используйте:
ActionController::Base.class_eval do
include SomethingFromMineGemModule
# or:
def hello_from_gem
'Hey people!'
end
end
Я смог ссылаться на ApplicationController с обратным вызовом инициализатора.
код gem, который подклассы/ссылки ApplicationController:
class GemApplicationController < ApplicationController
before_filter :method_to_call
def method_to_call
#your code here
end
end
обратный вызов кода gem для создания контроллера подкласса:
module GemName
def self.load_gem_application_controller
require "path/to/gem_application_controller"
end
end
rails_app/конфигурации/Инициализаторы/gem_name.rb
GemName.load_gem_application_controller
Затем есть контроллеры, которые используют этот подкласс класса GemApplicationController
class SpecialCaseController < GemApplicationController
# this will inherit from the gem controller,
# which inherits from the rails_app ApplicationController
end