Skip to content

Instantly share code, notes, and snippets.

@zinovyev
Created March 28, 2019 21:34
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zinovyev/bc73943c31a3e0d4585d9d05341339c3 to your computer and use it in GitHub Desktop.
Save zinovyev/bc73943c31a3e0d4585d9d05341339c3 to your computer and use it in GitHub Desktop.
Rails helper for loading controller specific assets managed by Webpacker
module WebpackerHelper
def page_pack_tags
join_paths(application_pack_tags,
controller_pack_tags)
end
def application_pack_tags
join_paths(attempt_to_find(:stylesheet, 'application'),
attempt_to_find(:javascript, 'application'))
end
def controller_pack_tags
join_paths(attempt_to_find(:stylesheet, controller_pack_lookup),
attempt_to_find(:javascript, controller_pack_lookup))
end
private
def join_paths(*paths)
paths.select(&:present?).join("\n\n").html_safe
end
def controller_pack_lookup
@controller_pack_lookup ||= begin
postfix = action_name.in?(%w[new create edit update]) ? "_form" : ""
"#{controller_path}#{postfix}"
end
end
def attempt_to_find(asset_type, asset_name)
case asset_type.to_sym
when :stylesheet then
stylesheet_pack_tag(asset_name.to_s, media: :all)
when :javascript then
javascript_pack_tag(asset_name.to_s)
else
nil
end
rescue Webpacker::Manifest::MissingEntryError => e
message = "Webpacker can't find file #{asset_name} of type #{asset_type}"
logger.debug(message)
nil
end
end
@DiegoOrejuela
Copy link

I like this code ❤️ . do you still use it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment