class Primalize::Many
Public Class Methods
add_attributes(attrs)
click to toggle source
# File lib/primalize/many.rb, line 12 def self.add_attributes attrs return if attrs.none? attrs.each do |attr, serializer_class| if serializer_class.nil? raise TypeError, "Serializer for #{self}##{attr} cannot be nil" end end @attributes.merge! attrs end
attributes(attrs={})
click to toggle source
# File lib/primalize/many.rb, line 5 def self.attributes attrs={} @attributes ||= {} add_attributes attrs @attributes end
enumerable(serializer_class)
click to toggle source
# File lib/primalize/many.rb, line 29 def self.enumerable serializer_class Class.new(Enumerable) do define_method :call do @enumerable.map { |item| serializer_class.new(item).call } end define_singleton_method :inspect do "enumerable(#{serializer_class.inspect})" end define_singleton_method :attributes do serializer_class.attributes end end end
inherited(klass)
click to toggle source
Pass on our attributes to child classes
# File lib/primalize/many.rb, line 25 def self.inherited klass klass.attributes attributes end
inspect()
click to toggle source
# File lib/primalize/many.rb, line 83 def self.inspect attrs = attributes .map { |attr, serializer| "#{attr}: #{serializer.inspect}" } .join(', ') "#{name}(#{attrs})" end
new(attributes)
click to toggle source
# File lib/primalize/many.rb, line 91 def initialize attributes validate_attributes! attributes @attributes = attributes end
optional(serializer_class)
click to toggle source
# File lib/primalize/many.rb, line 45 def self.optional serializer_class Class.new(Optional) do define_method :initialize do |object| return if object.nil? @object = object @serializer = serializer_class.new(object) end end end
Public Instance Methods
call()
click to toggle source
# File lib/primalize/many.rb, line 117 def call self.class.attributes.each_with_object({}) do |(attr, serializer_class), hash| hash[attr] = serializer_class.new(@attributes.fetch(attr)).call end end
to_csv(attr)
click to toggle source
# File lib/primalize/many.rb, line 127 def to_csv attr CSV.generate do |csv| result = call[attr] csv << self.class.attributes[attr].attributes.keys case result when Hash csv << result.values when Array result.each do |hash| csv << hash.values end end end end
to_json()
click to toggle source
# File lib/primalize/many.rb, line 123 def to_json call.to_json end
validate_attributes!(attributes)
click to toggle source
# File lib/primalize/many.rb, line 97 def validate_attributes! attributes attr_map = self.class.attributes all_required_attributes_provided = attr_map .each_key .all? do |key| attributes[key] || (attr_map[key].superclass == Optional) end unless all_required_attributes_provided non_nil_keys = attributes .select { |_attr, value| value } .map { |attr, _value| attr } missing_keys = self.class.attributes.keys - non_nil_keys raise ArgumentError, "#{self.class} is missing the following keys: #{missing_keys.map(&:inspect).join(', ')}" end end