lib/lookbook/preview.rb in lookbook-1.0.0.beta.4 vs lib/lookbook/preview.rb in lookbook-1.0.0.beta.5
- old
+ new
@@ -120,18 +120,19 @@
def exists?(path)
!!find(path)
end
- def clear_cache
- @previews = nil
+ def any?
+ all.any?
end
def all
load_previews if preview_files.size > ViewComponent::Preview.descendants.size
- return @previews if @previews.present?
+ @previews = nil if cache_stale?
+ return @previews unless @previews.nil?
previews = ViewComponent::Preview.descendants.map do |p|
new(p)
rescue
Rails.logger.error "[lookbook] error instantiating preview\n#{exception.full_message}"
@@ -142,19 +143,48 @@
Rails.logger.error "[lookbook] preview error\n#{error.full_message}\n"
end
end
sorted_previews = previews.compact.sort_by { |preview| [preview.position, preview.label] }
- @previews ||= PreviewCollection.new(sorted_previews)
+ @previews = PreviewCollection.new(sorted_previews)
+ mark_as_cached if Lookbook.config.listen == true
+ @previews
end
def errors
@errors ||= []
end
+ def clear_cache
+ cache_dir = File.dirname(cache_marker_path)
+ FileUtils.mkdir_p(cache_dir) unless File.exists?(cache_dir)
+ File.write(cache_marker_path, Time.now.to_i)
+ end
+
protected
+ def cache_marker_path
+ Rails.root.join("tmp/cache/lookbook-previews")
+ end
+
+ def cache_stale?
+ return false if !File.exists?(cache_marker_path)
+ cache_timestamp = File.read(cache_marker_path).to_i
+ if @last_cache_timestamp.nil? || cache_timestamp > @last_cache_timestamp
+ @last_cache_timestamp = cache_timestamp
+ true
+ else
+ false
+ end
+ end
+
+ def mark_as_cached
+ cache_dir = File.dirname(cache_marker_path)
+ FileUtils.mkdir_p(cache_dir) unless File.exists?(cache_dir)
+ File.write(cache_marker_path, Time.now)
+ end
+
def load_previews
@errors = []
preview_files.each do |file|
require_dependency file[:path]
rescue SyntaxError, StandardError => exception
@@ -164,10 +194,10 @@
file_name: file[:rel_path],
file_path: file[:path])
)
end
end
-
+
def preview_files
files = Array(Lookbook.config.preview_paths).map do |preview_path|
Dir["#{preview_path}/**/*preview.rb"].map do |path|
{
path: path,