lib/xpose/decorated.rb in xpose-0.1.5 vs lib/xpose/decorated.rb in xpose-0.1.6

- old
+ new

@@ -1,53 +1,55 @@ module Xpose class Decorated - attr_accessor :conf + attr_reader :conf - def initialize(**args) - @conf = ::Xpose::Configuration.build(args) - raise MissingParameter if conf.name.nil? - decorate_self if conf.decorate == :self + def initialize(**options) + @conf = ::Xpose::Configuration.new(options.merge(permissive: true)) end - def call(instance) - v = instance.send(conf.method_name) + def value(instance, v) + return v unless shall_decorate?(instance, v) if conf.decorator == :infer infer(v) elsif Class === conf.decorator - decorator.new(v) - elsif decorator.respond_to?(:call) - decorator.call(v) - elsif Symbol === decorator - decorator.to_s.singularize.capitalize.constantize.new(v) + conf.decorator.new(v) + elsif conf.decorator.respond_to?(:call) + conf.decorator.call(v) + elsif Symbol === conf.decorator && class_exists?(klass_from_symbol) + klass_from_symbol.new(v) else - raise StandardError.new('Unknown decorator') + raise UnknownDecoratorError.new(conf.decorator) end end private - def decorate_self - conf.decorated_name = conf.name - conf.decorated_method_name = conf.method_name - conf.decorated_instance_variable_name = conf.instance_variable_name + def shall_decorate?(instance, v) + return conf.decorate if [true, false].include?(conf.decorate) + raise UnknownOptionsError.new(:decorate) unless conf.decorate.respond_to?(:call) + instance.instance_exec &conf.decorate end def infer(v) if v.respond_to?(:decorate) v.decorate - elsif class_exists?(klass) - klass.new(v) + elsif class_exists?(klass_from_model) + klass_from_model.new(v) else - raise UnknownDecoratorError + raise UnknownDecoratorError.new(conf.decorator) end end - def klass - @klass ||= "#{conf.singularized_name.capitalize}Decorator".constantize + def klass_from_symbol + conf.decorator.to_s.singularize.capitalize.constantize end + def klass_from_model + "#{conf.model}Decorator".constantize + end + def class_exists?(class_name) - Module.const_get(class_name).is_a?(Class) + Module.const_get(class_name.to_s).is_a?(Class) rescue NameError return false end end end