module EitilWrapper module ControllerDecorator private def decorate(dec_item, dec_method: nil, dec_class: nil, **dec_kwargs) all_args_to_ivars binding set_ivars :dec_class, :decorator, :dec_method send_to_decorator rescue NameError => e puts "EitilWrapper::ControllerDecorator => rescuing uninitialised constant #{e.name}, returning the object's default JSON instead." return dec_item.as_json end def send_to_decorator @decorator.send(@dec_method, @dec_item) rescue NoMethodError => e inform_no_method_for_decorator_error @dec_item end def inform_no_method_for_decorator_error message = "Warning: NoMethodError for #{@dec_class}##{@dec_method}, returned @dec_item instead." Logger.new("#{Rails.root}/log/decorator_log.log").warn message warn message end def set_dec_method @dec_method = @dec_method || derived_dec_method || :base end def derived_dec_method return unless respond_to? :params return :app if @decorator.respond_to?(:app) && params["isMobile"] return :web if @decorator.respond_to?(:web) && params["isWeb"] end def set_dec_class @dec_class = @dec_class ? manual_set_dec_class : derived_dec_class end def manual_set_dec_class "#{@dec_class}Decorator".constantize end def derived_dec_class "#{@dec_item.class.name}Decorator".constantize end def set_decorator @dec_class.new **ivars end # Converts the controller_ivars, given in your main application's configuration, # into an hash. If no controller_ivars, continue with converting, in order to avoid # issues due to differing data types. def controller_ivars return {} unless Eitil.controller_ivars.any? Eitil.controller_ivars.map do |ivar| { ivar => instance_variable_get("@#{ivar.to_s}") } end.inject &:merge end def ivars @dec_kwargs.any? ? controller_ivars.merge(@dec_kwargs) : controller_ivars end end end