lib/alba/resource.rb in alba-1.0.1 vs lib/alba/resource.rb in alba-1.1.0

- old
+ new

@@ -26,13 +26,15 @@ module InstanceMethods attr_reader :object, :params # @param object [Object] the object to be serialized # @param params [Hash] user-given Hash for arbitrary data - def initialize(object, params: {}) + # @param within [Hash] determines what associations to be serialized. If not set, it serializes all associations. + def initialize(object, params: {}, within: true) @object = object @params = params.freeze + @within = within DSLS.each_key { |name| instance_variable_set("@#{name}", self.class.public_send(name)) } end # Serialize object into JSON string # @@ -128,12 +130,32 @@ when Symbol object.public_send attribute when Proc instance_exec(object, &attribute) when Alba::One, Alba::Many - attribute.to_hash(object, params: params) + within = check_within + return unless within + + attribute.to_hash(object, params: params, within: within) else raise ::Alba::Error, "Unsupported type of attribute: #{attribute.class}" + end + end + + def check_within + case @within + when Hash # Traverse within tree + @within.fetch(_key.to_sym, nil) + when Array # within tree ends with Array + @within.find { |item| item.to_sym == _key.to_sym } # Check if at least one item in the array matches current resource + when Symbol # within tree could end with Symbol + @within == _key.to_sym # Check if the symbol matches current resource + when true # In this case, Alba serializes all associations. + true + when nil, false # In these cases, Alba stops serialization here. + false + else + raise Alba::Error, "Unknown type for within option: #{@within.class}" end end def collection? @object.is_a?(Enumerable)