You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A hook to invoke the custom generator with scaffolding or with controller's generators
# lib/generators/rails/policy/hooks.rbrequire'rails/generators'require'rails/generators/rails/scaffold/scaffold_generator'require'rails/generators/rails/controller/controller_generator'Rails::Generators::ScaffoldGenerator.hook_for:policy,default: true,type: :boolean# invoke with scaffolding generatorsRails::Generators::ControllerGenerator.hook_for:policy,default: true,type: :boolean# invoke with the controllers' generator.
require "rails/railtie"
require "rails/generators"
module CustomPolicyGenerator
module ControllerGenerator
extend ActiveSupport::Concern
included do
hook_for :custom_policy, in: nil, default: true, type: :boolean do |generator|
invoke generator, [name.singularize]
end
end
end
module ScaffoldControllerGenerator
extend ActiveSupport::Concern
included do
hook_for :custom_policy, in: nil, default: true, type: :boolean
end
end
end
module ActiveModel
class Railtie < Rails::Railtie
generators do |app|
Rails::Generators.configure! app.config.generators
Rails::Generators::ControllerGenerator.include CustomPolicyGenerator::ControllerGenerator
Rails::Generators::ScaffoldControllerGenerator.include CustomPolicyGenerator::ScaffoldControllerGenerator
end
end
end
Rails.application.config.generators do |g|
g.policy false
g.custom_policy true
end
module Rails
class CustomPolicyGenerator < Rails::Generators::NamedBase
# source_root File.expand_path("templates", __dir__)
def create_policy
template "policy.rb", File.join("app/policies", class_path, "#{file_name}_policy.rb")
end
hook_for :test_framework
end
end
module Rspec
class CustomPolicyGenerator < Rails::Generators::NamedBase
# source_root File.expand_path("templates", __dir__)
def create_policy_spec
template "policy_spec.rb", File.join("spec/policies", class_path, "#{file_name}_policy_spec.rb")
end
end
end
Placed template files in
lib/templates/rails/custom_policy/policy.rb.tt
lib/templates/rspec/custom_policy/policy_spec.rb.tt
module ActiveModel
class Railtie < Rails::Railtie
generators do |app|
Rails::Generators.configure! app.config.generators
Rails::Generators::ControllerGenerator.include CustomPolicyGenerator::ControllerGenerator
Rails::Generators::ScaffoldControllerGenerator.include CustomPolicyGenerator::ScaffoldControllerGenerator
end
end
end
is the best way but outside of that, Rails::Generators::ScaffoldControllerGenerator is not defined and I am forced to use a require. If I use the requires:
Thanks yall. I wrote a blogpost to cover what ended up working for me. I did end up needing the requires, but I wasn't using custom templates so not sure if it breaks that like you mentioned.
That is my guess too. What should be done instead?