Skip to content

Commit 58f9dd2

Browse files
author
Nicholas Barone
committed
Rake task for generating stories from component previews
1 parent ddeb3ca commit 58f9dd2

File tree

5 files changed

+62
-4
lines changed

5 files changed

+62
-4
lines changed

lib/rails/storybook.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
require_relative "../storybook.rb"
2+
# TODO: Fix the gem naming, etc

lib/storybook.rb

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
require "storybook/version"
2+
require "storybook/preview"
3+
require "storybook/railtie" if defined?(Rails::Railtie)
24

3-
module Storybook
4-
class Error < StandardError; end
5-
# Your code goes here...
6-
end
5+
module Storybook; end

lib/storybook/preview.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
module Storybook
2+
module Preview
3+
def self.included(base)
4+
base.extend ClassMethods
5+
end
6+
7+
module ClassMethods
8+
def to_csf
9+
{ title: component_name, stories: stories }
10+
end
11+
12+
def stories
13+
instance_methods(false).collect { |name| story(name) }
14+
end
15+
16+
def story(name)
17+
{ name:, parameters: { server: { id: "#{component_name&.underscore}/#{name}" } } }
18+
end
19+
20+
def component_name
21+
$1 if name =~ /(.+Component)(?=Preview)/
22+
end
23+
end
24+
end
25+
end

lib/storybook/railtie.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
require "storybook"
2+
require "rails"
3+
4+
# https://gist.github.com/ntamvl/7a6658b4cd82d6fbd15434f0a9953411
5+
module Storybook
6+
class Railtie < Rails::Railtie
7+
railtie_name :storybook
8+
9+
rake_tasks do
10+
path = File.expand_path(__dir__)
11+
Dir.glob("#{path}/tasks/**/*.rake").each { |f| load f }
12+
end
13+
end
14+
end

lib/storybook/tasks/stories.rake

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
namespace :storybook do
2+
desc "Write CSF JSON stories for all Stories"
3+
task stories: :environment do
4+
previews_dir = Rails.root.join("test/components/previews")
5+
Dir.glob("#{previews_dir}/**/*_preview.rb").each { |file| require file }
6+
7+
stories = ViewComponent::Preview.descendants.map do |preview|
8+
[ preview.component_name&.underscore, preview.to_csf ] if preview < Storybook::Preview
9+
end
10+
11+
stories_dir = "stories"
12+
stories.each do |path, story|
13+
File.open(Rails.root.join("#{stories_dir}/#{path}.stories.json"), "w") do |f|
14+
f.write(JSON.pretty_generate(story))
15+
end
16+
end
17+
end
18+
end

0 commit comments

Comments
 (0)