Skip to content

Commit aa1cfe0

Browse files
committed
Allow values of attributes to be delegated. This allows the json api resource attribute to
easily have a different name without having to define a method for it.
1 parent 9e7d68d commit aa1cfe0

2 files changed

Lines changed: 6 additions & 5 deletions

File tree

lib/jsonapi/resource.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -399,11 +399,11 @@ def attribute(attr, options = {})
399399
@_attributes ||= {}
400400
@_attributes[attr] = options
401401
define_method attr do
402-
@model.public_send(attr)
402+
@model.public_send(options[:delegate] ? options[:delegate].to_sym : attr)
403403
end unless method_defined?(attr)
404404

405405
define_method "#{attr}=" do |value|
406-
@model.public_send "#{attr}=", value
406+
@model.public_send "#{options[:delegate] ? options[:delegate].to_sym : attr}=", value
407407
end unless method_defined?("#{attr}=")
408408
end
409409

test/unit/resource/resource_test.rb

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ class NoMatchAbstractResource < JSONAPI::Resource
3333
class CatResource < JSONAPI::Resource
3434
attribute :name
3535
attribute :breed
36+
attribute :kind, :delegate => :breed
3637

3738
has_one :mother, class_name: 'Cat'
3839
has_one :father, class_name: 'Cat'
@@ -173,7 +174,7 @@ def test_model_alternate
173174
def test_class_attributes
174175
attrs = CatResource._attributes
175176
assert_kind_of(Hash, attrs)
176-
assert_equal(attrs.keys.size, 3)
177+
assert_equal(attrs.keys.size, 4)
177178
end
178179

179180
def test_class_relationships
@@ -253,14 +254,14 @@ def test_updatable_fields_does_not_include_id
253254
# TODO: Please remove after `updateable_fields` is removed
254255
def test_updateable_fields_delegates_to_updatable_fields_with_deprecation
255256
ActiveSupport::Deprecation.silence do
256-
assert_empty(CatResource.updateable_fields(nil) - [:mother, :father, :name, :breed])
257+
assert_empty(CatResource.updateable_fields(nil) - [:mother, :father, :name, :breed, :kind])
257258
end
258259
end
259260

260261
# TODO: Please remove after `createable_fields` is removed
261262
def test_createable_fields_delegates_to_creatable_fields_with_deprecation
262263
ActiveSupport::Deprecation.silence do
263-
assert_empty(CatResource.createable_fields(nil) - [:mother, :father, :name, :breed, :id])
264+
assert_empty(CatResource.createable_fields(nil) - [:mother, :father, :name, :breed, :id, :kind])
264265
end
265266
end
266267

0 commit comments

Comments
 (0)