Skip to content

Commit

Permalink
Fix respecting a class when it already exists
Browse files Browse the repository at this point in the history
  • Loading branch information
santib committed Jun 28, 2022
1 parent a12fedf commit 3a334a5
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 8 deletions.
4 changes: 4 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ AllCops:
Lint/ConstantDefinitionInBlock:
Enabled: false

Lint/Void:
Exclude:
- spec/ar2dto/has_dto_spec.rb

Layout/LineLength:
Max: 120

Expand Down
1 change: 1 addition & 0 deletions ar2dto.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,5 @@ Gem::Specification.new do |spec|
spec.add_development_dependency "rspec", "~> 3.9.0"
spec.add_development_dependency "rubocop", "~> 1.28.2"
spec.add_development_dependency "sqlite3", "~> 1.4.2"
spec.add_development_dependency "zeitwerk", "~> 2.6.0"
end
8 changes: 5 additions & 3 deletions lib/ar2dto/has_dto.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ def has_dto(options = {})
include ::AR2DTO::HasDTO::InstanceMethods
ar2dto.setup_config(options)

return if ar2dto.namespace.const_defined?(ar2dto.class_name)

ar2dto.namespace.const_set(ar2dto.class_name, AR2DTO::DTO[self])
begin
ar2dto.namespaced_class_name.constantize
rescue NameError
ar2dto.namespace.const_set(ar2dto.class_name, AR2DTO::DTO[self])
end
end

# @api public
Expand Down
6 changes: 6 additions & 0 deletions spec/ar2dto/has_dto_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,23 @@

RSpec.describe ".has_dto" do
it "creates a new DTO class" do
User # autoload class

expect(Object.const_defined?("UserDTO")).to be true

expect(UserDTO.superclass).to eq AR2DTO::DTO
end

it "creates the new DTO class in the correct namespace" do
Shop::Order # autoload class

expect(Shop.const_defined?("OrderDTO")).to be true
end

context "when the class already exists" do
it "does not create a new class" do
Person # autoload class

expect(Object.const_defined?("PersonDTO")).to be true

expect(PersonDTO.superclass).to_not eq AR2DTO::DTO
Expand Down
10 changes: 5 additions & 5 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@

require "support/active_model"
require "support/schema"
require "support/fixtures/car"
require "support/fixtures/person_dto"
require "support/fixtures/person"
require "support/fixtures/shop/order"
require "support/fixtures/user"
require "zeitwerk"
loader = Zeitwerk::Loader.new
loader.inflector.inflect "person_dto" => "PersonDTO"
loader.push_dir("spec/support/fixtures")
loader.setup

RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
Expand Down

0 comments on commit 3a334a5

Please sign in to comment.