Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,21 @@ class SerializableGenerator < ::Rails::Generators::NamedBase
# TODO(beauby): Implement versioning.

def copy_serializable_file
fail "#{class_name} model not found." unless model_exists?

template 'serializable.rb.erb',
File.join('app/serializable', class_path,
"#{serializable_file_name}.rb")
end

private

def model_exists?
Rails.application.eager_load!
models = ApplicationRecord.descendants.map(&:name)
!!models.find { |model_name| model_name == class_name }
end

def serializable_file_name
"serializable_#{file_name}"
end
Expand All @@ -22,7 +30,6 @@ def serializable_class_name
end

def model_klass
# TODO(beauby): Ensure the model class exists.
class_name.safe_constantize
end

Expand Down
43 changes: 43 additions & 0 deletions spec/serializable_generator_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
require 'rails_helper'
require 'rails/generators'
require_relative File.expand_path("../../lib/generators/jsonapi/serializable/serializable_generator.rb", __FILE__)

describe Jsonapi::SerializableGenerator do
with_model :User, superclass: ApplicationRecord, scope: :all do
table do |t|
t.string :name
t.string :email
end
end

before do
@test_case = Rails::Generators::TestCase.new(:fake_test_case)
@test_case.class.tests(described_class)
@test_case.class.destination(File.expand_path("../tmp", File.dirname(__FILE__)))
@test_case.send(:prepare_destination)
end

context "passing an existent model" do
let(:model_name) { "User" }

it "creates a serializable resource" do
@test_case.assert_no_file "app/serializable/serializable_user.rb"
@test_case.run_generator([model_name])
@test_case.assert_file "app/serializable/serializable_user.rb", /SerializableUser/
end
end

context "passing an nonexistent model" do
let(:model_name) { "Dummy" }

it "raises an error" do
expect { @test_case.run_generator([model_name]) }.to raise_error(RuntimeError, "Dummy model not found.")
end

it "does not create a serializable resource" do
@test_case.assert_no_file "app/serializable/serializable_dummy.rb" do
@test_case.run_generator([model_name])
end
end
end
end