Skip to content

Commit

Permalink
[Feat] render_serialized_json now works with root_key and meta
Browse files Browse the repository at this point in the history
These options are passed to `serialize` method.
  • Loading branch information
okuramasafumi committed Dec 7, 2024
1 parent d387990 commit 198f631
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
9 changes: 5 additions & 4 deletions lib/alba/railtie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,14 @@ class Railtie < Rails::Railtie
Alba.inflector = :active_support

ActiveSupport.on_load(:action_controller) do
define_method(:serialize) do |obj, with: nil, &block|
with.nil? ? Alba.resource_with(obj, &block) : with.new(obj)
define_method(:serialize) do |obj, with: nil, root_key: nil, meta: {}, &block|
resource = with.nil? ? Alba.resource_with(obj, &block) : with.new(obj)
resource.to_json(root_key: root_key, meta: meta)
end

define_method(:render_serialized_json) do |obj, with: nil, &block|
define_method(:render_serialized_json) do |obj, with: nil, root_key: nil, meta: {}, &block|
json = with.nil? ? Alba.resource_with(obj, &block) : with.new(obj)
render json: json
render json: json.to_json(root_key: root_key, meta: meta)
end
end
end
Expand Down
24 changes: 24 additions & 0 deletions test/dependencies/railties_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,18 @@ def index
end
end

class MyFoosController < ActionController::Base
def show
foo = Foo.new(1, 'foo')
render json: serialize(foo, root_key: 'foo')
end

def index
foo = Foo.new(1, 'foo')
render_serialized_json([foo], with: FooResource, root_key: 'foos', meta: {total: 1})
end
end

Check failure

Code scanning / CodeQL

CSRF protection not enabled High test

Potential CSRF vulnerability due to forgery protection not being enabled.

Foo = Struct.new(:id, :name)

class FooResource
Expand Down Expand Up @@ -94,6 +106,18 @@ def test_foos_api_controller_index
assert_equal '[{"id":1,"name":"foo"}]', controller.response_body.first
end

def test_foos_controller_show_with_options
controller = controller_instance(MyFoosController)
controller.show
assert_equal '{"foo":{"id":1,"name":"foo"}}', controller.response_body.first
end

def test_foos_controller_index_with_options
controller = controller_instance(MyFoosController)
controller.index
assert_equal '{"foos":[{"id":1,"name":"foo"}],"meta":{"total":1}}', controller.response_body.first
end

private

def controller_instance(controller_class)
Expand Down

0 comments on commit 198f631

Please sign in to comment.