Skip to content

Commit

Permalink
Merge pull request #14 from gadabout/feature/add-related-to-changesets
Browse files Browse the repository at this point in the history
Added ability to add relationships to changesets.
  • Loading branch information
Chris Dosé committed Oct 18, 2016
2 parents d1eca3a + 1463a28 commit 37438a4
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 4 deletions.
9 changes: 8 additions & 1 deletion lib/lurch/changeset.rb
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
module Lurch
class Changeset
attr_reader :id, :type, :attributes
attr_reader :id, :type, :attributes, :relationships

def initialize(type, attributes = {})
is_resource = type.is_a?(Resource)
@type = is_resource ? type.type : Lurch.normalize_type(type)
@id = is_resource ? type.id : nil
@attributes = attributes
@relationships = {}
end

def add_related(relationship_key, related_resources)
@relationships[relationship_key.to_sym] = related_resources
self
end

def inspect
attrs = ["id: #{id.inspect}"]
attrs = attrs.concat attributes.map { |name, value| "#{name}: #{value.inspect}" }
attrs = attrs.concat relationships.map { |name, value| "#{name}: #{value.inspect}" }
inspection = attrs.join(", ")
"#<#{self.class}[#{Inflecto.classify(type)}] #{inspection}>"
end
Expand Down
13 changes: 11 additions & 2 deletions lib/lurch/payload_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ def resource_object_for(resource)
{
"id" => resource.id,
"type" => Inflecto.dasherize(resource.type.to_s),
"attributes" => attributes_for(resource)
"attributes" => attributes_for(resource),
"relationships" => relationships_for(resource)
}.reject { |_, v| v.nil? || (v.respond_to?(:empty?) && v.empty?) }
end

Expand All @@ -32,9 +33,17 @@ def attributes_for(resource)
dasherize_keys(resource.attributes)
end

def relationships_for(resource)
return {} if @resource_identifier_only
dasherize_keys(resource.relationships) do |value|
PayloadBuilder.new(value, true).build
end
end

def dasherize_keys(attributes)
attributes.each_with_object({}) do |(key, value), hash|
hash[Inflecto.dasherize(key.to_s)] = value
new_value = block_given? ? yield(value) : value
hash[Inflecto.dasherize(key.to_s)] = new_value
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion lib/lurch/version.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module Lurch
VERSION = "0.0.13".freeze
VERSION = "0.0.14".freeze
end
4 changes: 4 additions & 0 deletions spec/lurch/changeset_spec.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
RSpec.describe Lurch::Changeset do
let(:changeset) { Lurch::Changeset.new(:people) }

describe "#add_related" do
pending "TODO"
end

describe "#inspect" do
subject { changeset.inspect }
it { is_expected.to be_a(String) }
Expand Down

0 comments on commit 37438a4

Please sign in to comment.