Skip to content

Commit

Permalink
Convert all settings objects to the subclass of Config::Options
Browse files Browse the repository at this point in the history
To support utility methods like `#to_h`, `#dig` and so on, this changes
the all settings objects to the subclass of Config::Options.

refs: ruby/gem_rbs_collection#636
  • Loading branch information
tk0miya committed Aug 19, 2024
1 parent 217781a commit ee982e1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 18 deletions.
18 changes: 12 additions & 6 deletions lib/rbs_config/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,16 @@ def generate
methods = generate_methods(config)

format <<~RBS
class #{class_name}
#{classes.join("\n")}
#{methods.join("\n")}
module Config
module Generated
class #{class_name} < ::Config::Options
#{classes.join("\n")}
#{methods.join("\n")}
end
end
end
#{class_name}: Config::Generated::#{class_name}
RBS
end

Expand All @@ -49,7 +55,7 @@ def generate_classes(config)
methods = generate_methods(value)

<<~RBS
class #{key.camelize}
class #{key.camelize} < ::Config::Options
#{classes.join("\n")}
#{methods.join("\n")}
end
Expand All @@ -60,14 +66,14 @@ class #{key.camelize}

def generate_methods(config)
config.map do |key, value|
"def self.#{key}: () -> #{stringify_type(key, value)}"
"def #{key}: () -> #{stringify_type(key, value)}"
end
end

def stringify_type(name, value)
case value
when Hash
"singleton(#{name.camelize})"
name.camelize
when Array
types = value.map { |v| stringify_type(name, v) }.uniq
"Array[#{types.join(" | ")}]"
Expand Down
30 changes: 18 additions & 12 deletions spec/rbs_config/config_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,21 +31,27 @@
end
let(:expected) do
<<~RBS
class Settings
class Foo
def self.bar: () -> Integer
def self.baz: () -> bool
end
module Config
module Generated
class Settings < ::Config::Options
class Foo < ::Config::Options
def bar: () -> Integer
def baz: () -> bool
end
class Quux
def self.lorem: () -> Integer
def self.ipsum: () -> Integer
end
class Quux < ::Config::Options
def lorem: () -> Integer
def ipsum: () -> Integer
end
def self.foo: () -> singleton(Foo)
def self.qux: () -> Array[String]
def self.quux: () -> Array[singleton(Quux)]
def foo: () -> Foo
def qux: () -> Array[String]
def quux: () -> Array[Quux]
end
end
end
Settings: Config::Generated::Settings
RBS
end

Expand Down

0 comments on commit ee982e1

Please sign in to comment.