Skip to content

Commit

Permalink
Enable support for Solidus engines conditionally
Browse files Browse the repository at this point in the history
  • Loading branch information
aldesantis committed Jan 31, 2020
1 parent 128fd45 commit af42b93
Showing 1 changed file with 41 additions and 12 deletions.
53 changes: 41 additions & 12 deletions lib/solidus_support/engine_extensions/decorators.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,33 +4,62 @@ module SolidusSupport
module EngineExtensions
module Decorators
def self.included(engine)
engine.extend ClassMethods

engine.class_eval do
extend ClassMethods
config.to_prepare(&method(:activate).to_proc)
end
end

module ClassMethods
def activate
base_path = root.join('app/decorators')

if Rails.respond_to?(:autoloaders) && Rails.autoloaders.main
# Add decorators folder to the Rails autoloader. This
# allows Zeitwerk to resolve decorators paths correctly,
# when used.
Dir.glob(base_path.join('*')) do |decorators_folder|
# Add decorators folder to the Rails autoloader. This tells Zeitwerk to treat paths
# such as app/decorators/controllers as roots.
Dir.glob(decorators_root.join('*')) do |decorators_folder|
Rails.autoloaders.main.push_dir(decorators_folder)
end
end

# Load decorator files. This is needed since they are
# never explicitely referenced in the application code
# and won't be loaded by default. We need them to be
# executed anyway to extend exisiting classes.
Dir.glob(base_path.join('**/*.rb')) do |decorator_path|
load_decorators_from(decorators_root)

enable_engine_support('backend') if SolidusSupport.backend_available?
enable_engine_support('frontend') if SolidusSupport.frontend_available?
enable_engine_support('api') if SolidusSupport.api_available?
end

private

# Loads decorator files.
#
# This is needed since they are never explicitly referenced in the application code and
# won't be loaded by default. We need them to be executed regardless in order to decorate
# existing classes.
def load_decorators_from(path)
Dir.glob(path.join('**/*.rb')) do |decorator_path|
require_dependency(decorator_path)
end
end

# Returns the root for this engine's decorators.
#
# @return [Path]
def decorators_root
root.join('app/decorators')
end

# Enables support for a Solidus engine.
#
# This will simply tell Rails to load lib/controllers/[engine] and lib/views/[engine], as
# well as loading the decorators from lib/decorators/[engine].
#
# @see #load_decorators_path
def enable_engine_support(engine)
paths['app/controllers'] << "lib/controllers/#{engine}"
paths['app/views'] << "lib/views/#{engine}"

load_decorators_from(root.join("lib/decorators/#{engine}"))
end
end
end
end
Expand Down

0 comments on commit af42b93

Please sign in to comment.