Skip to content

Commit

Permalink
Rake task for generating stories from component previews
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicholas Barone committed Aug 9, 2024
1 parent ddeb3ca commit 58f9dd2
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 4 deletions.
2 changes: 2 additions & 0 deletions lib/rails/storybook.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
require_relative "../storybook.rb"
# TODO: Fix the gem naming, etc
7 changes: 3 additions & 4 deletions lib/storybook.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
require "storybook/version"
require "storybook/preview"
require "storybook/railtie" if defined?(Rails::Railtie)

module Storybook
class Error < StandardError; end
# Your code goes here...
end
module Storybook; end
25 changes: 25 additions & 0 deletions lib/storybook/preview.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
module Storybook
module Preview
def self.included(base)
base.extend ClassMethods
end

module ClassMethods
def to_csf
{ title: component_name, stories: stories }
end

def stories
instance_methods(false).collect { |name| story(name) }
end

def story(name)
{ name:, parameters: { server: { id: "#{component_name&.underscore}/#{name}" } } }
end

def component_name
$1 if name =~ /(.+Component)(?=Preview)/
end
end
end
end
14 changes: 14 additions & 0 deletions lib/storybook/railtie.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
require "storybook"
require "rails"

# https://gist.github.com/ntamvl/7a6658b4cd82d6fbd15434f0a9953411
module Storybook
class Railtie < Rails::Railtie
railtie_name :storybook

rake_tasks do
path = File.expand_path(__dir__)
Dir.glob("#{path}/tasks/**/*.rake").each { |f| load f }
end
end
end
18 changes: 18 additions & 0 deletions lib/storybook/tasks/stories.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
namespace :storybook do
desc "Write CSF JSON stories for all Stories"
task stories: :environment do
previews_dir = Rails.root.join("test/components/previews")
Dir.glob("#{previews_dir}/**/*_preview.rb").each { |file| require file }

stories = ViewComponent::Preview.descendants.map do |preview|
[ preview.component_name&.underscore, preview.to_csf ] if preview < Storybook::Preview
end

stories_dir = "stories"
stories.each do |path, story|
File.open(Rails.root.join("#{stories_dir}/#{path}.stories.json"), "w") do |f|
f.write(JSON.pretty_generate(story))
end
end
end
end

0 comments on commit 58f9dd2

Please sign in to comment.