lib/alba/resource.rb in alba-0.5.0 vs lib/alba/resource.rb in alba-0.6.0

- old
+ new

@@ -5,16 +5,21 @@ require 'alba/serializers/default_serializer' module Alba # This module represents what should be serialized module Resource - DSLS = [:_attributes, :_serializer].freeze + DSLS = [:_attributes, :_serializer, :_key].freeze def self.included(base) base.class_eval do # Initialize DSLS.each do |name| - initial = name == :_serializer ? nil : {} + initial = case name + when :_attributes + {} + when :_serializer, :_name + nil + end instance_variable_set("@#{name}", initial) unless instance_variable_defined?("@#{name}") end end base.include InstanceMethods base.extend ClassMethods @@ -36,20 +41,25 @@ when Proc inline_extended_serializer(with) else raise ArgumentError, 'Unexpected type for with, possible types are Class or Proc' end - serializer.new(serializable_hash).serialize + serializer.new(self).serialize end - def serializable_hash - @_attributes.transform_values do |attribute| + def serializable_hash(with_key: true) + serializable_hash = @_attributes.transform_values do |attribute| attribute.to_hash(@_resource) end + with_key && @_key ? {@_key => serializable_hash} : serializable_hash end alias to_hash serializable_hash + def key + @_key || self.class.name.delete_suffix('Resource').downcase.gsub(/:{2}/, '_').to_sym + end + private def inline_extended_serializer(with) klass = ::Alba::Serializers::DefaultSerializer.clone klass.class_eval(&with) @@ -83,9 +93,13 @@ @_attributes[name.to_sym] = Many.new(name: name, resource: resource, &block) end def serializer(name) @_serializer = name <= Alba::Serializer ? name : nil + end + + def key(key) + @_key = key.to_sym end end end end