lib/looksist/hashed.rb in looksist-0.3.1 vs lib/looksist/hashed.rb in looksist-0.3.2

- old
+ new

@@ -13,46 +13,46 @@ after = opts[:after] @rules ||= {} (@rules[after] ||= []) << opts unless @rules[after].length > 1 - define_method("#{after}_with_inject") do |*args| - hash = send("#{after}_without_inject".to_sym, *args) - self.class.instance_variable_get(:@rules)[after].each do |opts| - if opts[:at].nil? or opts[:at].is_a? String - hash = self.class.update_using_json_path(hash, opts) - else - self.class.inject_attributes_at(hash[opts[:at]], opts) - end + if self.singleton_methods.include?(after) + inject_class_methods(after) + else + inject_instance_methods(after) + end + end + end + + def inject_instance_methods(after) + define_method("#{after}_with_inject") do |*args| + hash = send("#{after}_without_inject".to_sym, *args) + self.class.instance_variable_get(:@rules)[after].each do |opts| + if opts[:at].nil? or opts[:at].is_a? String + hash = self.class.update_using_json_path(hash, opts) + else + self.class.inject_attributes_at(hash[opts[:at]], opts) end - hash end - alias_method_chain after, :inject + hash end + alias_method_chain after, :inject end - def class_inject(opts) - raise 'Incorrect usage' unless [:after, :using, :populate].all? { |e| opts.keys.include? e } - - after = opts[:after] - @rules ||= {} - (@rules[after] ||= []) << opts - - unless @rules[after].length > 1 - define_singleton_method("#{after}_with_inject") do |*args| - hash = send("#{after}_without_inject".to_sym, *args) - @rules[after].each do |opts| - if opts[:at].nil? or opts[:at].is_a? String - hash = update_using_json_path(hash, opts) - else - inject_attributes_at(hash[opts[:at]], opts) - end + def inject_class_methods(after) + define_singleton_method("#{after}_with_inject") do |*args| + hash = send("#{after}_without_inject".to_sym, *args) + @rules[after].each do |opts| + if opts[:at].nil? or opts[:at].is_a? String + hash = update_using_json_path(hash, opts) + else + inject_attributes_at(hash[opts[:at]], opts) end - hash end - self.singleton_class.send(:alias_method_chain, after, :inject) + hash end + self.singleton_class.send(:alias_method_chain, after, :inject) end def inject_attributes_at(hash_offset, opts) return hash_offset if hash_offset.nil? or hash_offset.empty? keys = hash_offset[opts[:using]] @@ -69,10 +69,10 @@ JsonPath.for(hash.with_indifferent_access).gsub!(opts[:at]) do |i| i.is_a?(Array) ? inject_attributes_for(i, opts) : inject_attributes_at(i, opts) unless (i.nil? or i.empty?) i end else - inject_attributes_at(hash, opts) + inject_attributes_at(hash, opts) end.to_hash.deep_symbolize_keys else inject_attributes_for(hash, opts) end