Module: Eco::API::Common::ClassHelpers
- Included in:
- ClassHierarchy
- Defined in:
- lib/eco/api/common/class_helpers.rb
Instance Method Summary collapse
- #class_resolver(name, klass) ⇒ Object
-
#new_class(name, inherits:, parent_space: nil) {|child_class| ... } ⇒ Class
If the class for
nameexists, it returns it. - #resolve_class(klass, exception: true) ⇒ Object
-
#to_constant(key) ⇒ String
Helper to normalize
keyinto a correctrubyconstant name.
Instance Method Details
#class_resolver(name, klass) ⇒ Object
6 7 8 9 |
# File 'lib/eco/api/common/class_helpers.rb', line 6 def class_resolver(name, klass) define_singleton_method(name) { resolve_class(klass) } define_method(name) { self.class.resolve_class(klass) } end |
#new_class(name, inherits:, parent_space: nil) {|child_class| ... } ⇒ Class
If the class for name exists, it returns it. Otherwise it generates it.
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/eco/api/common/class_helpers.rb', line 46 def new_class(name, inherits:, parent_space: nil) name = name.to_sym.freeze class_name = to_constant(name) parent_space = parent_space ? resolve_class(parent_space) : self full_class_name = "#{parent_space}::#{class_name}" unless target_class = resolve_class(full_class_name, exception: false) target_class = Class.new(inherits) parent_space.const_set class_name, target_class end target_class.tap do |klass| yield(klass) if block_given? end end |
#resolve_class(klass, exception: true) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/eco/api/common/class_helpers.rb', line 11 def resolve_class(klass, exception: true) @resolved ||= {} @resolved[klass] ||= case klass when Class klass when String begin Kernel.const_get(klass) rescue NameError => e raise if exception end when Symbol resolve_class(self.send(klass)) else raise "Unknown class: #{klass}" if exception end end |
#to_constant(key) ⇒ String
Helper to normalize key into a correct ruby constant name
33 34 35 36 37 |
# File 'lib/eco/api/common/class_helpers.rb', line 33 def to_constant(key) str_name = key.to_s.strip.split(/[\-\_ ]/i).compact.map do |str| str.slice(0).upcase + str.slice(1..-1).downcase end.join("") end |