diff --git a/jsonapi_parser.gemspec b/jsonapi_parser.gemspec index 9ae3903..ed6653a 100644 --- a/jsonapi_parser.gemspec +++ b/jsonapi_parser.gemspec @@ -17,9 +17,9 @@ Gem::Specification.new do |spec| spec.test_files = spec.files.grep(%r{^(spec)/}) spec.require_paths = ['lib'] - spec.add_dependency 'json', '~>1.8' + spec.add_dependency 'json', '~> 1.8' - spec.add_development_dependency 'rake', '>=0.9' - spec.add_development_dependency 'rspec', '~>3.4' + spec.add_development_dependency 'rake', '>= 0.9' + spec.add_development_dependency 'rspec', '~> 3.4' spec.add_development_dependency 'simplecov' end diff --git a/lib/jsonapi/include_directive.rb b/lib/jsonapi/include_directive.rb index 7562e95..0f2884e 100644 --- a/lib/jsonapi/include_directive.rb +++ b/lib/jsonapi/include_directive.rb @@ -12,6 +12,8 @@ module JSONAPI # @example 'posts.**' # => Include related posts, and all the included # posts' related resources, and their related resources, recursively. class IncludeDirective + attr_reader :options, :hash + # @param include_args (see Parser.include_hash_from_include_args) def initialize(include_args, options = {}) include_hash = Parser.parse_include_args(include_args) @@ -40,6 +42,28 @@ def [](key) end end + # @param another_directive [IncludeDirective] + # @return [IncludeDirective] + def merge(other) + dup.merge!(other) + end + + # @param another_directive [IncludeDirective] + # @return [IncludeDirective] + def merge!(other) + fail ArgumentError, + "parameter MUST be an IncludeDirective" unless + other.is_a?(IncludeDirective) + + hash = to_hash + Parser.deep_merge!(hash, other.to_hash) + + merge_result = IncludeDirective.new(hash, options) + @hash = merge_result.hash + @options = merge_result.options + self + end + # @return [Hash{Symbol => Hash}] def to_hash @hash.each_with_object({}) do |(key, value), hash| diff --git a/spec/merge_spec.rb b/spec/merge_spec.rb new file mode 100644 index 0000000..2427005 --- /dev/null +++ b/spec/merge_spec.rb @@ -0,0 +1,41 @@ +require 'jsonapi/include_directive' + +describe JSONAPI::IncludeDirective, '.merge' do + it 'works' do + d1 = JSONAPI::IncludeDirective.new( + { + post: { + comments: { + references: [:url] + }, + author: [:address] + } + } + ) + d2 = JSONAPI::IncludeDirective.new( + { + post: { + comments: [:length], + author: {}, + created_at: {} + } + } + ) + expected = JSONAPI::IncludeDirective.new( + { + post: { + comments: { + references: [:url], + length: {} + }, + author: [:address], + created_at: {} + } + } + ).to_hash + + expect(d1.merge(d2).to_hash).to eq(expected) + d1.merge!(d2) + expect(d1.to_hash).to eq(expected) + end +end