# encoding: utf-8 module Hexx # @api hide # The module contains helper classes and modules. # # All the helpers injects some code into corresponding class or module. # # The content of the module is not a part of API, but its implementation # details. module Helpers # @api hide # @abstract # The base class for attribute injection. # # The objects of the class validates its parameters and adds # attribute's getter and setter into the target class or module. class Base < Struct.new(:target, :name) # @api hide # @!method add(target, name) # Injects an attribute to the target class. # # @param [Module] target The class or module to inject the attribute to. # @param [String, Symbol] name The name of the attribute. # @raise (see Hexx::Helpers::Base#validate) # @return [Hexx::Helpers::Base] the base class object. def self.add(*args) new(*args).validate.add_getter.add_setter end # @api hide # @!attribute target # The class to inject the attribute to # @return [Class] the target for the injection # @api hide # @!attribute name # The name of the attribute to be created in a target class # @return [Class] the name of the attribute # @api hide # Validates parameters of the dependency declaration. # # @raise (see Hexx::Helpers::Base#check_target) # @raise (see Hexx::Helpers::Base#check_name_type) # @raise (see Hexx::Helpers::Base#check_name_value) # @return [Hexx::Helpers::Base] +self+ def validate check_target check_name_type check_name_value self end # @api hide # Adds the parameter getter to the +target+ instance # @return [Hexx::Helpers::Base] +self+ def add_getter target.class_eval getter self end # @api hide # Adds the parameter setter to the +target+ instance # @return [Hexx::Helpers::Base] +self+ def add_setter target.class_eval setter self end private # @abstract # @return [String] the getter definition def getter "" end # @abstract # @return [String] the setter definition def setter "" end # @api hide # @raise [TypeError] if a target to add the instance parameter to # is not a class. def check_target return if target.is_a? Class fail TypeError.new "#{ target.inspect } is not a class" end # @api hide # @raise [TypeError] if the attribute name is neither a string nor symbol. def check_name_type return if name.is_a?(String) || name.is_a?(Symbol) fail TypeError.new "#{ name.inspect } is neither string nor symbol" end # @api hide # @raise [AttributeError] it the name is blank. def check_name_value return unless name.to_s == "" fail ArgumentError.new "Dependency should have a name" end end end end