lib/ecoportal/api/common/content/class_helpers.rb in ecoportal-api-v2-1.1.8 vs lib/ecoportal/api/common/content/class_helpers.rb in ecoportal-api-v2-2.0.0
- old
+ new
@@ -39,11 +39,11 @@
# Helper to normalize `key` into a correct `ruby` **constant name**
# @note it removes namespace syntax `::`
# @param key [String, Symbol] to be normalized
# @return [String] a correct constant name
def to_constant(key)
- key.to_s.strip.split(/::/).compact.map do |str|
+ key.to_s.strip.split('::').compact.map do |str|
str.slice(0).upcase + str.slice(1..-1)
end.join.split(/[\-\_ :]+/i).compact.map do |str|
str.slice(0).upcase + str.slice(1..-1)
end.join
end
@@ -65,19 +65,21 @@
end
# If the class for `name` exists, it returns it. Otherwise it generates it.
# @param name [String, Symbol] the name of the new class
# @param inherits [Class] the parent class to _inherit_ from
- # @param namespace [Class, String] an existing `constant` (class or module) the new class will be namespaced on
+ # @param namespace [Class, String] an existing `constant` (class or module)
+ # the new class will be namespaced on
# @yield [child_class] configure the new class
# @yieldparam child_class [Class] the new class
# @return [Class] the new generated class
def new_class(name = "Child#{uid}", inherits: self, namespace: inherits)
- name = name.to_s.to_sym.freeze
- class_name = to_constant(name)
+ name = name.to_s.to_sym.freeze
+ class_name = to_constant(name)
+ target_class = resolve_class("#{namespace}::#{class_name}", exception: false)
- unless target_class = resolve_class("#{namespace}::#{class_name}", exception: false)
+ unless target_class
target_class = Class.new(inherits)
Kernel.const_get(namespace.to_s).const_set class_name, target_class
end
target_class.tap do |klass|
@@ -129,12 +131,14 @@
end
# Builds the attr_reader and attr_writer of `attrs` and registers the associated instance variable as inheritable.
def inheritable_attrs(*attrs)
attrs.each do |attr|
- class_eval %(
- class << self; attr_accessor :#{attr} end
- )
+ class_eval <<-DEF_CLSS_ATTR, __FILE__, __LINE__ + 1
+ class << self # class << self
+ attr_accessor :#{attr} # attr_accessor :coolio
+ end # end
+ DEF_CLSS_ATTR
end
inheritable_class_vars(*attrs)
end
# This callback method is called whenever a subclass of the current class is created.