Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document how to support camelcase attributes #417

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 76 additions & 1 deletion lib/active_resource/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,48 @@ module ActiveResource
# self.proxy = "https://user:[email protected]:8080"
# end
#
# == Attribute Schema
#
# Active Resource objects respond to attributes returned by +known_attributes+.
# Resource instances populate the +known_attributes+ array during calls to +initialize+ and +load,
# or when data is fetched from the remote system.
#
# Instances will not respond to attribute methods until they are loaded.
#
# Resource classes can define the set of +known_attributes+ by defining a +schema+:
#
# class Person < ActiveResource::Base
# schema do
# # define each attribute separately
# attribute :name, :string
# attribute :age, :integer
# end
# end
#
# p = Person.new
# p.respond_to? :name # => true
# p.respond_to? :name= # => true
# p.respond_to? :age # => true
# p.respond_to? :age= # => true
# p.name # => nil
# p.age # => nil
#
# Attribute-types must be one of: <tt>string, text, integer, float, decimal, datetime, timestamp, time, date, binary, boolean</tt>
#
# To transform data fetched from the remote system prior to attribute
# assignment, override the +load+ method:
#
# class Person < ActiveResource::Base
# def load(attributes, remove_root = false, persisted = false)
# attributes = attributes.deep_transform_keys { |key| key.to_s.underscore }
#
# super
# end
# end
#
# p = Person.new(:firstName => 'Ryan', :lastName => 'Daigle')
# p.first_name # => 'Ryan'
# p.last_name # => 'Daigle'
#
# == Life cycle methods
#
Expand Down Expand Up @@ -1425,7 +1467,23 @@ def exists?

# Returns the serialized string representation of the resource in the configured
# serialization format specified in ActiveResource::Base.format. The options
# applicable depend on the configured encoding format.
# applicable depend on the configured encoding format, and are forwarded to
# the corresponding serializer method.
#
# ActiveResource::Formats::XmlFormat will forward options <tt>#to_xml</tt> and
# ActiveResource::Formats::JsonFormat will forward options <tt>#to_json</tt>.
#
# Override the +serializable_hash+ method to customize how the
# attribute keys and values are encoded to a JSON or XML string.
#
# class Person < ActiveResource::Base
# def serializable_hash(options = {})
# super.deep_transform_keys! { |key| key.camelcase(:lower) }
# end
# end
#
# A resource that relies on a custom format must respond to a serializer method
# that corresponds to the format's +extension+ method.
def encode(options = {})
send("to_#{self.class.format.extension}", options)
end
Expand Down Expand Up @@ -1466,6 +1524,23 @@ def reload
# your_supplier = Supplier.new
# your_supplier.load(my_attrs)
# your_supplier.save
#
# Override +load+ to transform the attributes prior to loading.
#
# class Person < ActiveResource::Base
# def load(attributes, remove_root = false, persisted = false)
# attributes = attributes.deep_transform_keys { |key| key.to_s.underscore }
#
# super
# end
# end
#
# camelcase_attrs = { :firstName => 'Marty', :favorite_colors => ['red', 'green', 'blue'] }
#
# person = Person.new
# person.load(camelcase_attrs)
# person.first_name # => 'Marty'
# person.favorite_colors # => ['red', 'green', 'blue']
def load(attributes, remove_root = false, persisted = false)
unless attributes.respond_to?(:to_hash)
raise ArgumentError, "expected attributes to be able to convert to Hash, got #{attributes.inspect}"
Expand Down
12 changes: 12 additions & 0 deletions test/cases/base/load_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,18 @@ def test_load_simple_hash
assert_equal @matz.stringify_keys, @person.load(@matz).attributes
end

def test_load_simple_camelcase_hash
camelcase_person = Camelcase::Person.new(likesHats: true)

assert_predicate camelcase_person, :likes_hats?
end

def test_load_nested_camelcase_hash
camelcase_person = Camelcase::Person.new(address: { streetName: "12345 Street" })

assert_equal "12345 Street", camelcase_person.address.street_name
end

def test_load_object_with_implicit_conversion_to_hash
assert_equal @matz.stringify_keys, @person.load(FakeParameters.new(@matz)).attributes
end
Expand Down
10 changes: 10 additions & 0 deletions test/cases/base_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1471,6 +1471,16 @@ def test_to_json_with_element_name
Person.element_name = old_elem_name
end

def test_to_json_with_camelcase
joe_camel = Camelcase::Person.new(name: "Joe", likes_hats: true)
encode = joe_camel.encode
json = joe_camel.to_json

assert_equal encode, json
assert_match %r{"name":"Joe"}, json
assert_match %r{"likesHats":true}, json
end

def test_to_param_quacks_like_active_record
new_person = Person.new
assert_nil new_person.to_param
Expand Down
14 changes: 14 additions & 0 deletions test/fixtures/person.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,17 @@ class ProfileData < ActiveResource::Base
self.site = "http://external.profile.data.nl"
end
end

module Camelcase
class Person < ::Person
def load(attributes, *args)
attributes = attributes.deep_transform_keys { |key| key.to_s.underscore }

super
end

def serializable_hash(options = {})
super.deep_transform_keys! { |key| key.camelcase(:lower) }
end
Comment on lines +19 to +27
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this the best way to achieve this outcome? When learning about the library, my first instinct was to tackle name casing at the JsonFormat level.

Unfortunately, since #encode is implemented in terms of #to_json, and not JsonFormat.encode, a custom format that inherited from JsonFormat had no effect.

Is there a more canonical way to extend or configure the pre-existing JsonFormat module to more elegantly handle this?

Could it be worthwhile to explore changing the Base#encode implementation to incorporate self.class.format.encode?

end
end
Loading