lib/svelte_on_rails/view_helpers.rb
# lib/svelte_on_rails/view_helpers.rb module SvelteOnRails module ViewHelpers def svelte_component(filename, props = {}) support = SvelteOnRails::Lib::ViewHelperSupport.new(filename, props, request, false) support.debug_log("Rendering component: #{filename}") log_message = '?' log_message = "Rendered #{support.filename}.svelte #{'as empty element that will be mounted on the client side' unless support.ssr?}" res = render_component(support) support.log_rendering(log_message) res end def cached_svelte_component(filename, props = {}) support = SvelteOnRails::Lib::ViewHelperSupport.new(filename, props, request, true) log_message = '?' redis = support.conf.redis_instance cached_content = redis.get(support.cache_key) # TTL if support.debug? support.debug_log("Rendering component: «#{filename}», cache_key: «#{support.custom_cache_key}»") support.debug_log("Redis configuration: #{support.conf.redis_cache_store}") ttl = redis.ttl(support.cache_key) key_stat = if cached_content.present? 'has content' elsif redis.exists(support.cache_key) 'exists but no content' else 'not exists' end ttl_stat = if redis.exists(support.cache_key) ", ttl was: #{ttl} seconds, now set to: #{support.redis_expiration_seconds} seconds" end support.debug_log("Cache key: «#{support.cache_key}» (#{key_stat}#{ttl_stat})") end redis.expire(support.cache_key, support.redis_expiration_seconds) res = if cached_content log_message = "Returned #{support.filename}.svelte from cache" cached_content.html_safe else log_message = "Rendered #{support.filename}.svelte and stored to cache" support.debug_log("cache recalculating for key: #{support.cache_key}") r = render_component(support) support.debug_log("cache recalculated") # redis.scan_each(match: "#{support.cache_key_primary}:*") do |key| # redis.del(key) # support.debug_log("deleted cache, pattern: «#{support.cache_key_primary}:*», key: #{key.sub("#{support.cache_key_primary}:", '[..]')}") # end redis.set(support.cache_key, r) r end support.log_rendering(log_message) res end private def render_component(support) if support.ssr? ssr_result = support.render_ssr content_tag(:div, support.html_options) do concat(content_tag(:style, ssr_result['css'], type: 'text/css')) concat(ssr_result['html'].html_safe) end else content_tag(:div, support.html_options) {} end end end end