pax_global_header 0000666 0000000 0000000 00000000064 13512322311 0014503 g ustar 00root root 0000000 0000000 52 comment=433c0c646f7ad9d330343526f6b2c2bee5dcc295
active_model_serializers-0.10.10/ 0000775 0000000 0000000 00000000000 13512322311 0016711 5 ustar 00root root 0000000 0000000 active_model_serializers-0.10.10/.github/ 0000775 0000000 0000000 00000000000 13512322311 0020251 5 ustar 00root root 0000000 0000000 active_model_serializers-0.10.10/.github/ISSUE_TEMPLATE.md 0000664 0000000 0000000 00000001067 13512322311 0022762 0 ustar 00root root 0000000 0000000 #### Expected behavior vs actual behavior
#### Steps to reproduce
*(e.g., detailed walkthrough, runnable script, example application)*
#### Environment
ActiveModelSerializers Version *(commit ref if not on tag)*:
Output of `ruby -e "puts RUBY_DESCRIPTION"`:
OS Type & Version:
Integrated application and version *(e.g., Rails, Grape, etc)*:
#### Backtrace
*(e.g., provide any applicable backtraces from your application)*
#### Additonal helpful information
*(e.g., Gemfile.lock, configurations, PR containing a failing test, git bisect results)*
active_model_serializers-0.10.10/.github/PULL_REQUEST_TEMPLATE.md 0000664 0000000 0000000 00000000160 13512322311 0024047 0 ustar 00root root 0000000 0000000 #### Purpose
#### Changes
#### Caveats
#### Related GitHub issues
#### Additional helpful information
active_model_serializers-0.10.10/.gitignore 0000664 0000000 0000000 00000000515 13512322311 0020702 0 ustar 00root root 0000000 0000000 *.gem
*.rbc
.bundle
.config
.yardoc
Gemfile.lock
Gemfile.local
InstalledFiles
_yardoc
coverage
doc/
lib/bundler/man
pkg
Vagrantfile
.vagrant
rdoc
spec/reports
test/tmp
test/version_tmp
tmp
*.swp
.ruby-version
.ruby-gemset
vendor/bundle
tags
# silly macs
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db
active_model_serializers-0.10.10/.rubocop.yml 0000664 0000000 0000000 00000003774 13512322311 0021176 0 ustar 00root root 0000000 0000000 AllCops:
TargetRubyVersion: 2.1
Exclude:
- !ruby/regexp /(vendor|bundle|bin|db|tmp)\/.*/
DisplayCopNames: true
DisplayStyleGuide: true
# https://github.com/bbatsov/rubocop/blob/master/manual/caching.md
# https://github.com/bbatsov/rubocop/blob/e8680418b351491e111a18cf5b453fc07a3c5239/config/default.yml#L60-L77
UseCache: true
CacheRootDirectory: tmp
Rails:
Enabled: true
Lint/NestedMethodDefinition:
Enabled: false
Exclude:
- test/action_controller/serialization_test.rb
Style/Alias:
EnforcedStyle: prefer_alias
Style/StringLiterals:
EnforcedStyle: single_quotes
Metrics/AbcSize:
Max: 35 # TODO: Lower to 15
Metrics/ClassLength:
Max: 261 # TODO: Lower to 100
Exclude:
- test/**/*.rb
Metrics/CyclomaticComplexity:
Max: 7 # TODO: Lower to 6
Metrics/LineLength:
Max: 251 # TODO: Lower to 80
Metrics/MethodLength:
Max: 106 # TODO: Lower to 10
Metrics/PerceivedComplexity:
Max: 9 # TODO: Lower to 7
Style/AlignParameters:
EnforcedStyle: with_fixed_indentation
Style/ClassAndModuleChildren:
EnforcedStyle: nested
Style/Documentation:
Enabled: false
Style/MissingElse:
Enabled: true
EnforcedStyle: case
Style/EmptyElse:
EnforcedStyle: empty
Style/FrozenStringLiteralComment:
Enabled: true
EnforcedStyle: always
Style/MultilineOperationIndentation:
EnforcedStyle: indented
Style/BlockDelimiters:
Enabled: true
EnforcedStyle: line_count_based
Style/SignalException:
EnforcedStyle: semantic
Style/TrailingCommaInLiteral:
EnforcedStyleForMultiline: no_comma
Style/ConditionalAssignment:
Enabled: false
Style/DotPosition:
EnforcedStyle: leading
########## test_helper.rb sanity
Style/EndBlock:
Exclude:
- test/test_helper.rb
Style/SpecialGlobalVars:
Exclude:
- test/test_helper.rb
Style/GlobalVars:
Exclude:
- test/test_helper.rb
Style/AndOr:
Exclude:
- test/test_helper.rb
- 'lib/active_model/serializer/lint.rb'
Style/Not:
Exclude:
- test/test_helper.rb
Style/ClassCheck:
Exclude:
- test/test_helper.rb
active_model_serializers-0.10.10/.simplecov 0000664 0000000 0000000 00000005773 13512322311 0020727 0 ustar 00root root 0000000 0000000 # https://github.com/colszowka/simplecov#using-simplecov-for-centralized-config
# see https://github.com/colszowka/simplecov/blob/master/lib/simplecov/defaults.rb
# vim: set ft=ruby
## DEFINE VARIABLES
@minimum_coverage = ENV.fetch('COVERAGE_MINIMUM') {
case (defined?(RUBY_ENGINE) && RUBY_ENGINE) || "ruby"
when 'jruby', 'rbx'
96.0
else
98.1
end
}.to_f.round(2)
# rubocop:disable Style/DoubleNegation
ENV['FULL_BUILD'] ||= ENV['CI']
@running_ci = !!(ENV['FULL_BUILD'] =~ /\Atrue\z/i)
@generate_report = @running_ci || !!(ENV['COVERAGE'] =~ /\Atrue\z/i)
@output = STDOUT
# rubocop:enable Style/DoubleNegation
## CONFIGURE SIMPLECOV
SimpleCov.profiles.define 'app' do
coverage_dir 'coverage'
load_profile 'test_frameworks'
add_group 'Libraries', 'lib'
add_group 'Long files' do |src_file|
src_file.lines.count > 100
end
class MaxLinesFilter < SimpleCov::Filter
def matches?(source_file)
source_file.lines.count < filter_argument
end
end
add_group 'Short files', MaxLinesFilter.new(5)
# Exclude these paths from analysis
add_filter '/config/'
add_filter '/db/'
add_filter 'tasks'
add_filter '/.bundle/'
end
## START TRACKING COVERAGE (before activating SimpleCov)
require 'coverage'
Coverage.start
## ADD SOME CUSTOM REPORTING AT EXIT
SimpleCov.at_exit do
next if $! and not ($!.kind_of? SystemExit and $!.success?)
header = "#{'*' * 20} SimpleCov Results #{'*' * 20}"
results = SimpleCov.result.format!.join("\n")
exit_message = <<-EOF
#{header}
{{RESULTS}}
{{FAILURE_MESSAGE}}
#{'*' * header.size}
EOF
percent = Float(SimpleCov.result.covered_percent)
if percent < @minimum_coverage
failure_message = <<-EOF
Spec coverage was not high enough: #{percent.round(2)}% is < #{@minimum_coverage}%
EOF
exit_message.sub!('{{RESULTS}}', results).sub!('{{FAILURE_MESSAGE}}', failure_message)
@output.puts exit_message
abort(failure_message) if @generate_report
elsif @running_ci
exit_message.sub!('{{RESULTS}}', results).sub!('{{FAILURE_MESSAGE}}', <<-EOF)
Nice job! Spec coverage (#{percent.round(2)}%) is still at or above #{@minimum_coverage}%
EOF
@output.puts exit_message
end
end
## CAPTURE CONFIG IN CLOSURE 'AppCoverage.start'
## to defer running until test/test_helper.rb is loaded.
# rubocop:disable Style/MultilineBlockChain
AppCoverage = Class.new do
def initialize(&block)
@block = block
end
def start
@block.call
end
end.new do
SimpleCov.start 'app'
if @generate_report
if @running_ci
require 'codeclimate-test-reporter'
@output.puts '[COVERAGE] Running with SimpleCov Simple Formatter and CodeClimate Test Reporter'
formatters = [
SimpleCov::Formatter::SimpleFormatter,
CodeClimate::TestReporter::Formatter
]
else
@output.puts '[COVERAGE] Running with SimpleCov HTML Formatter'
formatters = [SimpleCov::Formatter::HTMLFormatter]
end
else
formatters = []
end
SimpleCov.formatters = formatters
end
# rubocop:enable Style/MultilineBlockChain
active_model_serializers-0.10.10/.travis.yml 0000664 0000000 0000000 00000006530 13512322311 0021026 0 ustar 00root root 0000000 0000000 language: ruby
sudo: false
ruby_supported_versions:
- &ruby_2_1 2.1.10
- &ruby_2_2 2.2.10
- &ruby_2_3 2.3.8
- &ruby_2_4 2.4.6
- &ruby_2_5 2.5.5
- &ruby_2_6 2.6.3
- &ruby_head ruby-head
rails_supported_versions:
- &rails_4_1 RAILS_VERSION=4.1
- &rails_4_2 RAILS_VERSION=4.2
- &rails_5_0 RAILS_VERSION=5.0
- &rails_5_1 RAILS_VERSION=5.1
- &rails_5_2 RAILS_VERSION=5.2
- &rails_6_0_0_rc1 RAILS_VERSION=6.0.0.rc1
- &rails_master RAILS_VERSION=master
cache:
directories:
- vendor/bundle
before_install:
- "travis_retry gem update --system 2.7.9"
- "travis_retry gem install bundler -v '1.17.3'"
install: BUNDLER_VERSION=1.17.3 bundle install --path=vendor/bundle --retry=3 --jobs=3
script:
- bundle exec rake ci
after_success:
- codeclimate-test-reporter
env:
matrix:
- *rails_4_1
- *rails_4_2
- *rails_5_0
- *rails_5_1
- *rails_5_2
- *rails_6_0_0_rc1
- *rails_master
rvm:
- *ruby_2_1
- *ruby_2_2
- *ruby_2_3
- *ruby_2_4
- *ruby_2_5
- *ruby_2_6
- *ruby_head
branches:
only: 0-10-stable
matrix:
include:
- { rvm: jruby-9.1.13.0, jdk: oraclejdk8, env: "RAILS_VERSION=4.1 JRUBY_OPTS='--dev -J-Xmx1024M --debug'" }
- { rvm: jruby-9.1.13.0, jdk: oraclejdk8, env: "RAILS_VERSION=4.2 JRUBY_OPTS='--dev -J-Xmx1024M --debug'" }
- { rvm: jruby-9.1.13.0, jdk: oraclejdk8, env: "RAILS_VERSION=5.1 JRUBY_OPTS='--dev -J-Xmx1024M --debug'" }
# See JRuby currently failing on Rails 5+ https://github.com/jruby/activerecord-jdbc-adapter/issues/708
# - { rvm: jruby-9.1.13.0, jdk: oraclejdk8, env: "RAILS_VERSION=5.0 JRUBY_OPTS='--dev -J-Xmx1024M --debug'" }
# - { rvm: jruby-head, jdk: oraclejdk8, env: "RAILS_VERSION=5.1 JRUBY_OPTS='--dev -J-Xmx1024M --debug'" }
exclude:
- { rvm: *ruby_2_1, env: *rails_5_0 }
- { rvm: *ruby_2_1, env: *rails_5_1 }
- { rvm: *ruby_2_1, env: *rails_5_2 }
- { rvm: *ruby_2_1, env: *rails_6_0_0_rc1 }
- { rvm: *ruby_2_2, env: *rails_6_0_0_rc1 }
- { rvm: *ruby_2_3, env: *rails_6_0_0_rc1 }
- { rvm: *ruby_2_4, env: *rails_6_0_0_rc1 }
- { rvm: *ruby_2_1, env: *rails_master }
- { rvm: *ruby_2_2, env: *rails_master }
- { rvm: *ruby_2_3, env: *rails_master }
- { rvm: *ruby_2_4, env: *rails_master }
allow_failures:
- { rvm: *ruby_2_4, env: *rails_4_1 }
- { rvm: *ruby_2_5, env: *rails_4_1 }
- { rvm: *ruby_2_6, env: *rails_4_1 }
# allow RAILS_VERSION=master to fail against ruby 2.5+ until this gem supports RAILS_VERSION
# https://github.com/rails/rails/blob/master/RAILS_VERSION
# https://github.com/rails-api/active_model_serializers/blob/0-10-stable/active_model_serializers.gemspec#L24
- { rvm: *ruby_2_5, env: *rails_master }
- { rvm: *ruby_2_6, env: *rails_master }
- rvm: *ruby_head
# - { rvm: *ruby_head, env: *rails_4_1 }
# - { rvm: *ruby_head, env: *rails_4_2 }
# - { rvm: *ruby_head, env: *rails_5_0 }
# - { rvm: *ruby_head, env: *rails_5_1 }
# - { rvm: *ruby_head, env: *rails_5_2 }
# - { rvm: *ruby_head, env: *rails_6_0_0_rc1 }
# - { rvm: *ruby_head, env: *rails_master }
- rvm: jruby-head
# See JRuby currently failing on Rails 5+ https://github.com/jruby/activerecord-jdbc-adapter/issues/708
- { rvm: jruby-9.1.13.0, jdk: oraclejdk8, env: "RAILS_VERSION=5.1 JRUBY_OPTS='--dev -J-Xmx1024M --debug'" }
fast_finish: true
active_model_serializers-0.10.10/CHANGELOG.md 0000664 0000000 0000000 00000167022 13512322311 0020532 0 ustar 00root root 0000000 0000000 ## 0.10.x
### [master (unreleased)](https://github.com/rails-api/active_model_serializers/compare/v0.10.10...0-10-stable)
Breaking changes:
Features:
Fixes:
Misc:
### [v0.10.10 (2019-07-13)](https://github.com/rails-api/active_model_serializers/compare/v0.10.9...v0.10.10)
Fixes:
- [#2319](https://github.com/rails-api/active_model_serializers/pull/2319) Fixes #2316. (@kylekeesling)
- Fix Rails 6.0 deprication warnings
- update test fixture schema to use `timestamps` instead of `timestamp`
- [#2223](https://github.com/rails-api/active_model_serializers/pull/2223) Support Fieldset in Attributes/JSON adapters documented in [docs/general/fields.md](https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/fields.md) that worked partially before (@bf4)
- [#2337](https://github.com/rails-api/active_model_serializers/pull/2337) fix incorrect belongs_to serialization when foreign_key on object and belongs_to is blank (@InteNs)
- Fixes incorrect json-api generation when `jsonapi_use_foreign_key_on_belongs_to_relationship` is `true` and the relationship is blank
- [#2172](https://github.com/rails-api/active_model_serializers/pull/2172) Preserve the namespace when falling back to a superclass serializer
Misc:
- [#2327](https://github.com/rails-api/active_model_serializers/pull/2327) Add support for Ruby 2.6 on Travis CI (@wasifhossain)
- [#2304](https://github.com/rails-api/active_model_serializers/pull/2304) Slim down bundled gem by excluding test files and docs (@greysteil)
### [v0.10.9 (2019-02-08)](https://github.com/rails-api/active_model_serializers/compare/v0.10.8...v0.10.9)
Fixes:
- [#2288](https://github.com/rails-api/active_model_serializers/pull/2288)
Change the fetch method to deal with recyclable key cache strategy.
Fixes #2287. (@cintamani, @wasifhossain)
- [#2307](https://github.com/rails-api/active_model_serializers/pull/2307) Falsey attribute values should not be reevaluated.
Misc:
- [#2309](https://github.com/rails-api/active_model_serializers/pull/2309) Performance and memory usage fixes
### [v0.10.8 (2018-11-01)](https://github.com/rails-api/active_model_serializers/compare/v0.10.7...v0.10.8)
Features:
- [#2279](https://github.com/rails-api/active_model_serializers/pull/2279) Support condition options in serializer link statements
Fixes:
- [#2296](https://github.com/rails-api/active_model_serializers/pull/2296) Fixes #2295 (@Hirurg103)
- Fix finding of namespaced serializer and non-namespaced model.
- [#2289](https://github.com/rails-api/active_model_serializers/pull/2289) Fixes #2255 (@f-mer)
- Fix autoloading race condition, especially in Rails 5.
- [#2299](https://github.com/rails-api/active_model_serializers/pull/2299) Fixes #2270 (@chau-bao-long via #2276)
- Fix reflection thread-safety bug
### [v0.10.7 (2017-11-14)](https://github.com/rails-api/active_model_serializers/compare/v0.10.6...v0.10.7)
Regressions Fixed From v0.10.6:
- [#2211](https://github.com/rails-api/active_model_serializers/pull/2211). Fixes #2125, #2160. (@bf4)
- Fix polymorphic belongs_to tests; passes on v0.10.5, fails on v0.10.6
- Fix JSON:API polymorphic type regression from v0.10.5
- Fix JSON:API: for_type_and_id should always inflect_type
```
Should Serializer._type ever be inflected?
Right now, it won't be, but association.serializer._type will be inflected.
That's the current behavior.
```
- [#2216](https://github.com/rails-api/active_model_serializers/pull/2216). Fixes #2132, #2180. (@bf4)
- Fix JSON:API: Serialize resource type for unpersisted records (blank id)
- [#2218](https://github.com/rails-api/active_model_serializers/pull/2218). Fixes #2178. (@bf4)
- Fix JSON:API: Make using foreign key on belongs_to opt-in. No effect on polymorphic relationships.
```
# set to true to opt-in
ActiveModelSerializer.config.jsonapi_use_foreign_key_on_belongs_to_relationship = true
```
Features:
- [#2136](https://github.com/rails-api/active_model_serializers/pull/2136) Enable inclusion of sideloaded relationship objects by `key`. (@caomania)
- [#2021](https://github.com/rails-api/active_model_serializers/pull/2021) ActiveModelSerializers::Model#attributes. Originally in [#1982](https://github.com/rails-api/active_model_serializers/pull/1982). (@bf4)
- [#2130](https://github.com/rails-api/active_model_serializers/pull/2130) Allow serialized ID to be overwritten for belongs-to relationships. (@greysteil)
- [#2189](https://github.com/rails-api/active_model_serializers/pull/2189)
Update version constraint for jsonapi-renderer to `['>= 0.1.1.beta1', '< 0.3']`
(@tagliala)
Fixes:
- [#2022](https://github.com/rails-api/active_model_serializers/pull/2022) Mutation of ActiveModelSerializers::Model now changes the attributes. Originally in [#1984](https://github.com/rails-api/active_model_serializers/pull/1984). (@bf4)
- [#2200](https://github.com/rails-api/active_model_serializers/pull/2200) Fix deserialization of polymorphic relationships. (@dennis95stumm)
- [#2214](https://github.com/rails-api/active_model_serializers/pull/2214) Fail if unable to infer collection type with json adapter. (@jmeredith16)
- [#2149](https://github.com/rails-api/active_model_serializers/pull/2149) Always include self, first, last pagination link. (@mecampbellsoup)
- [#2179](https://github.com/rails-api/active_model_serializers/pull/2179) Fixes #2173, Pass block to Enumerator.new. (@drn)
Misc:
- [#2176](https://github.com/rails-api/active_model_serializers/pull/2176) Documentation for global adapter config. (@mrpinsky)
- [#2215](https://github.com/rails-api/active_model_serializers/pull/2215) Update `serializers.md` documentation to denote alternate use cases for `scope`. (@stratigos)
- [#2212](https://github.com/rails-api/active_model_serializers/pull/2212) Remove legacy has_many_embed_ids test. (@bf4)
### [v0.10.6 (2017-05-01)](https://github.com/rails-api/active_model_serializers/compare/v0.10.5...v0.10.6)
Fixes:
- [#1857](https://github.com/rails-api/active_model_serializers/pull/1857) JSON:API does not load belongs_to relation to get identifier id. (@bf4)
- [#2119](https://github.com/rails-api/active_model_serializers/pull/2119) JSON:API returns null resource object identifier when 'id' is null. (@bf4)
- [#2093](https://github.com/rails-api/active_model_serializers/pull/2093) undef problematic Serializer methods: display, select. (@bf4)
Misc:
- [#2104](https://github.com/rails-api/active_model_serializers/pull/2104) Documentation for serializers and rendering. (@cassidycodes)
- [#2081](https://github.com/rails-api/active_model_serializers/pull/2081) Documentation for `include` option in adapters. (@charlie-wasp)
- [#2120](https://github.com/rails-api/active_model_serializers/pull/2120) Documentation for association options: foreign_key, type, class_name, namespace. (@bf4)
### [v0.10.5 (2017-03-07)](https://github.com/rails-api/active_model_serializers/compare/v0.10.4...v0.10.5)
Breaking changes:
Features:
- [#2021](https://github.com/rails-api/active_model_serializers/pull/2021) ActiveModelSerializers::Model#attributes. Originally in [#1982](https://github.com/rails-api/active_model_serializers/pull/1982). (@bf4)
- [#2057](https://github.com/rails-api/active_model_serializers/pull/2057)
Update version constraint for jsonapi-renderer to `['>= 0.1.1.beta1', '< 0.2']`
(@jaredbeck)
Fixes:
- [#2022](https://github.com/rails-api/active_model_serializers/pull/2022) Mutation of ActiveModelSerializers::Model now changes the attributes. Originally in [#1984](https://github.com/rails-api/active_model_serializers/pull/1984). (@bf4)
Misc:
- [#2055](https://github.com/rails-api/active_model_serializers/pull/2055)
Replace deprecated dependency jsonapi with jsonapi-renderer. (@jaredbeck)
- [#2021](https://github.com/rails-api/active_model_serializers/pull/2021) Make test attributes explicit. Tests have Model#associations. (@bf4)
- [#1981](https://github.com/rails-api/active_model_serializers/pull/1981) Fix relationship link documentation. (@groyoh)
- [#2035](https://github.com/rails-api/active_model_serializers/pull/2035) Document how to disable the logger. (@MSathieu)
- [#2039](https://github.com/rails-api/active_model_serializers/pull/2039) Documentation fixes. (@biow0lf)
### [v0.10.4 (2017-01-06)](https://github.com/rails-api/active_model_serializers/compare/v0.10.3...v0.10.4)
Misc:
- [#2005](https://github.com/rails-api/active_model_serializers/pull/2005) Update jsonapi runtime dependency to 0.1.1.beta6, support Ruby 2.4. (@kofronpi)
- [#1993](https://github.com/rails-api/active_model_serializers/pull/1993) Swap out KeyTransform for CaseTransform gem for the possibility of native extension use. (@NullVoxPopuli)
### [v0.10.3 (2016-11-21)](https://github.com/rails-api/active_model_serializers/compare/v0.10.2...v0.10.3)
Fixes:
- [#1973](https://github.com/rails-api/active_model_serializers/pull/1973) Fix namespace lookup for collections and has_many relationships (@groyoh)
- [#1887](https://github.com/rails-api/active_model_serializers/pull/1887) Make the comment reflect what the function does (@johnnymo87)
- [#1890](https://github.com/rails-api/active_model_serializers/issues/1890) Ensure generator inherits from ApplicationSerializer when available (@richmolj)
- [#1922](https://github.com/rails-api/active_model_serializers/pull/1922) Make railtie an optional dependency in runtime (@ggpasqualino)
- [#1930](https://github.com/rails-api/active_model_serializers/pull/1930) Ensure valid jsonapi when relationship has no links or data (@richmolj)
Features:
- [#1757](https://github.com/rails-api/active_model_serializers/pull/1757) Make serializer lookup chain configurable. (@NullVoxPopuli)
- [#1968](https://github.com/rails-api/active_model_serializers/pull/1968) (@NullVoxPopuli)
- Add controller namespace to default controller lookup
- Provide a `namespace` render option
- document how set the namespace in the controller for implicit lookup.
- [#1791](https://github.com/rails-api/active_model_serializers/pull/1791) (@bf4, @youroff, @NullVoxPopuli)
- Added `jsonapi_namespace_separator` config option.
- [#1889](https://github.com/rails-api/active_model_serializers/pull/1889) Support key transformation for Attributes adapter (@iancanderson, @danbee)
- [#1917](https://github.com/rails-api/active_model_serializers/pull/1917) Add `jsonapi_pagination_links_enabled` configuration option (@richmolj)
- [#1797](https://github.com/rails-api/active_model_serializers/pull/1797) Only include 'relationships' when sideloading (@richmolj)
Fixes:
- [#1833](https://github.com/rails-api/active_model_serializers/pull/1833) Remove relationship links if they are null (@groyoh)
- [#1881](https://github.com/rails-api/active_model_serializers/pull/1881) ActiveModelSerializers::Model correctly works with string keys (@yevhene)
Misc:
- [#1767](https://github.com/rails-api/active_model_serializers/pull/1767) Replace raising/rescuing `CollectionSerializer::NoSerializerError`,
throw/catch `:no_serializer`. (@bf4)
- [#1839](https://github.com/rails-api/active_model_serializers/pull/1839) `fields` tests demonstrating usage for both attributes and relationships. (@NullVoxPopuli)
- [#1812](https://github.com/rails-api/active_model_serializers/pull/1812) add a code of conduct (@corainchicago)
- [#1878](https://github.com/rails-api/active_model_serializers/pull/1878) Cache key generation for serializers now uses `ActiveSupport::Cache.expand_cache_key` instead of `Array#join` by default and is also overridable. This change should be backward-compatible. (@markiz)
- [#1799](https://github.com/rails-api/active_model_serializers/pull/1799) Add documentation for setting the adapter. (@cassidycodes)
- [#1909](https://github.com/rails-api/active_model_serializers/pull/1909) Add documentation for relationship links. (@vasilakisfil, @NullVoxPopuli)
- [#1959](https://github.com/rails-api/active_model_serializers/pull/1959) Add documentation for root. (@shunsuke227ono)
- [#1967](https://github.com/rails-api/active_model_serializers/pull/1967) Improve type method documentation. (@yukideluxe)
### [v0.10.2 (2016-07-05)](https://github.com/rails-api/active_model_serializers/compare/v0.10.1...v0.10.2)
Fixes:
- [#1814](https://github.com/rails-api/active_model_serializers/pull/1814) Ensuring read_multi works with fragment cache
- [#1848](https://github.com/rails-api/active_model_serializers/pull/1848) Redefine associations on inherited serializers. (@EhsanYousefi)
Misc:
- [#1808](https://github.com/rails-api/active_model_serializers/pull/1808) Adds documentation for `fields` option. (@luizkowalski)
### [v0.10.1 (2016-06-16)](https://github.com/rails-api/active_model_serializers/compare/v0.10.0...v0.10.1)
Features:
- [#1668](https://github.com/rails-api/active_model_serializers/pull/1668) Exclude nil and empty links. (@sigmike)
- [#1426](https://github.com/rails-api/active_model_serializers/pull/1426) Add ActiveModelSerializers.config.default_includes (@empact)
Fixes:
- [#1754](https://github.com/rails-api/active_model_serializers/pull/1754) Fixes #1759, Grape integration, improves serialization_context
missing error message on pagination. Document overriding CollectionSerializer#paginated?. (@bf4)
Moved serialization_context creation to Grape formatter, so resource serialization works without explicit calls to the `render` helper method.
Added Grape collection tests. (@onomated)
- [#1287](https://github.com/rails-api/active_model_serializers/pull/1287) Pass `fields` options from adapter to serializer. (@vasilakisfil)
- [#1710](https://github.com/rails-api/active_model_serializers/pull/1710) Prevent association loading when `include_data` option
is set to `false`. (@groyoh)
- [#1747](https://github.com/rails-api/active_model_serializers/pull/1747) Improve jsonapi mime type registration for Rails 5 (@remear)
Misc:
- [#1734](https://github.com/rails-api/active_model_serializers/pull/1734) Adds documentation for conditional attribute (@lambda2)
- [#1685](https://github.com/rails-api/active_model_serializers/pull/1685) Replace `IncludeTree` with `IncludeDirective` from the jsonapi gem.
### [v0.10.0 (2016-05-17)](https://github.com/rails-api/active_model_serializers/compare/4a2d9853ba7...v0.10.0)
Breaking changes:
- [#1662](https://github.com/rails-api/active_model_serializers/pull/1662) Drop support for Rails 4.0 and Ruby 2.0.0. (@remear)
Features:
- [#1677](https://github.com/rails-api/active_model_serializers/pull/1677) Add `assert_schema`, `assert_request_schema`, `assert_request_response_schema`. (@bf4)
- [#1697](https://github.com/rails-api/active_model_serializers/pull/1697) Include actual exception message with custom exceptions;
`Test::Schema` exceptions are now `Minitest::Assertion`s. (@bf4)
- [#1699](https://github.com/rails-api/active_model_serializers/pull/1699) String/Lambda support for conditional attributes/associations (@mtsmfm)
- [#1687](https://github.com/rails-api/active_model_serializers/pull/1687) Only calculate `_cache_digest` (in `cache_key`) when `skip_digest` is false. (@bf4)
- [#1647](https://github.com/rails-api/active_model_serializers/pull/1647) Restrict usage of `serializable_hash` options
to the ActiveModel::Serialization and ActiveModel::Serializers::JSON interface. (@bf4)
Fixes:
- [#1700](https://github.com/rails-api/active_model_serializers/pull/1700) Support pagination link for Kaminari when no data is returned. (@iamnader)
- [#1726](https://github.com/rails-api/active_model_serializers/pull/1726) Adds polymorphic option to association definition which includes association type/nesting in serializer (@cgmckeever)
Misc:
- [#1673](https://github.com/rails-api/active_model_serializers/pull/1673) Adds "How to" guide on using AMS with POROs (@DrSayre)
- [#1730](https://github.com/rails-api/active_model_serializers/pull/1730) Adds documentation for overriding default serializer based on conditions (@groyoh/@cgmckeever)
### [v0.10.0.rc5 (2016-04-04)](https://github.com/rails-api/active_model_serializers/compare/v0.10.0.rc4...v0.10.0.rc5)
Breaking changes:
- [#1645](https://github.com/rails-api/active_model_serializers/pull/1645) Changed :dashed key transform to :dash. (@remear)
- [#1574](https://github.com/rails-api/active_model_serializers/pull/1574) Default key case for the JsonApi adapter changed to dashed. (@remear)
Features:
- [#1645](https://github.com/rails-api/active_model_serializers/pull/1645) Transform keys referenced in values. (@remear)
- [#1650](https://github.com/rails-api/active_model_serializers/pull/1650) Fix serialization scope options `scope`, `scope_name`
take precedence over `serialization_scope` in the controller.
Fix tests that required tearing down dynamic methods. (@bf4)
- [#1644](https://github.com/rails-api/active_model_serializers/pull/1644) Include adapter name in cache key so
that the same serializer can be cached per adapter. (@bf4 via #1346 by @kevintyll)
- [#1642](https://github.com/rails-api/active_model_serializers/pull/1642) Prefer object.cache_key over the generated
cache key. (@bf4 via #1346 by @kevintyll)
- [#1637](https://github.com/rails-api/active_model_serializers/pull/1637) Make references to 'ActionController::Base.cache_store' explicit
in order to avoid issues when application controllers inherit from 'ActionController::API'. (@ncuesta)
- [#1633](https://github.com/rails-api/active_model_serializers/pull/1633) Yield 'serializer' to serializer association blocks. (@bf4)
- [#1616](https://github.com/rails-api/active_model_serializers/pull/1616) SerializableResource handles no serializer like controller. (@bf4)
- [#1618](https://github.com/rails-api/active_model_serializers/issues/1618) Get collection root key for
empty collection from explicit serializer option, when possible. (@bf4)
- [#1574](https://github.com/rails-api/active_model_serializers/pull/1574) Provide key translation. (@remear)
- [#1494](https://github.com/rails-api/active_model_serializers/pull/1494) Make serializers serializalbe
(using the Attributes adapter by default). (@bf4)
- [#1550](https://github.com/rails-api/active_model_serializers/pull/1550) Add
Rails url_helpers to `SerializationContext` for use in links. (@remear, @bf4)
- [#1004](https://github.com/rails-api/active_model_serializers/pull/1004) JSON API errors object implementation.
- Only implements `detail` and `source` as derived from `ActiveModel::Error`
- Provides checklist of remaining questions and remaining parts of the spec.
- [#1515](https://github.com/rails-api/active_model_serializers/pull/1515) Adds support for symbols to the
`ActiveModel::Serializer.type` method. (@groyoh)
- [#1504](https://github.com/rails-api/active_model_serializers/pull/1504) Adds the changes missing from #1454
and add more tests for resource identifier and relationship objects. Fix association block with link
returning `data: nil`.(@groyoh)
- [#1372](https://github.com/rails-api/active_model_serializers/pull/1372) Support
cache_store.read_multi. (@LcpMarvel)
- [#1018](https://github.com/rails-api/active_model_serializers/pull/1018) Add more tests and docs for top-level links. (@leandrocp)
- [#1454](https://github.com/rails-api/active_model_serializers/pull/1454) Add support for
relationship-level links and meta attributes. (@beauby)
- [#1340](https://github.com/rails-api/active_model_serializers/pull/1340) Add support for resource-level meta. (@beauby)
Fixes:
- [#1657](https://github.com/rails-api/active_model_serializers/pull/1657) Add missing missing require "active_support/json". (@andreaseger)
- [#1661](https://github.com/rails-api/active_model_serializers/pull/1661) Fixes `read_attribute_for_serialization` not
seeing methods defined in serialization superclass (#1653, #1658, #1660), introduced in #1650. (@bf4)
- [#1651](https://github.com/rails-api/active_model_serializers/pull/1651) Fix deserialization of nil relationships. (@NullVoxPopuli)
- [#1480](https://github.com/rails-api/active_model_serializers/pull/1480) Fix setting of cache_store from Rails configuration. (@bf4)
Fix unintentional mutating of value in memory cache store. (@groyoh)
- [#1622](https://github.com/rails-api/active_model_serializers/pull/1622) Fragment cache changed from per-record to per-serializer.
Now, two serializers that use the same model may be separately cached. (@lserman)
- [#1478](https://github.com/rails-api/active_model_serializers/pull/1478) Cache store will now be correctly set when serializers are
loaded *before* Rails initializes. (@bf4)
- [#1570](https://github.com/rails-api/active_model_serializers/pull/1570) Fixed pagination issue with last page size. (@bmorrall)
- [#1516](https://github.com/rails-api/active_model_serializers/pull/1516) No longer return a nil href when only
adding meta to a relationship link. (@groyoh)
- [#1458](https://github.com/rails-api/active_model_serializers/pull/1458) Preserve the serializer
type when fragment caching. (@bdmac)
- [#1477](https://github.com/rails-api/active_model_serializers/pull/1477) Fix `fragment_cached?`
method to check if caching. (@bdmac)
- [#1501](https://github.com/rails-api/active_model_serializers/pull/1501) Adds tests for SerializableResource::use_adapter?,doc typos (@domitian)
- [#1488](https://github.com/rails-api/active_model_serializers/pull/1488) Require ActiveSupport's string inflections (@nate00)
Misc:
- [#1608](https://github.com/rails-api/active_model_serializers/pull/1608) Move SerializableResource to ActiveModelSerializers (@groyoh)
- [#1602](https://github.com/rails-api/active_model_serializers/pull/1602) Add output examples to Adapters docs (@remear)
- [#1557](https://github.com/rails-api/active_model_serializers/pull/1557) Update docs regarding overriding the root key (@Jwan622)
- [#1471](https://github.com/rails-api/active_model_serializers/pull/1471) [Cleanup] Serializer caching is its own concern. (@bf4)
- [#1482](https://github.com/rails-api/active_model_serializers/pull/1482) Document JSON API implementation defs and progress in class. (@bf4)
- [#1551](https://github.com/rails-api/active_model_serializers/pull/1551) Added codebeat badge (@korzonek)
- [#1527](https://github.com/rails-api/active_model_serializers/pull/1527) Refactor fragment cache class. (@groyoh)
- [#1560](https://github.com/rails-api/active_model_serializers/pull/1560) Update rubocop and address its warnings. (@bf4 @groyoh)
- [#1545](https://github.com/rails-api/active_model_serializers/pull/1545) Document how to pass arbitrary options to the
serializer (@CodedBeardedSignedTaylor)
- [#1496](https://github.com/rails-api/active_model_serializers/pull/1496) Run all branches against JRuby on CI (@nadavshatz)
- [#1559](https://github.com/rails-api/active_model_serializers/pull/1559) Add a deprecation DSL. (@bf4 @groyoh)
- [#1543](https://github.com/rails-api/active_model_serializers/pull/1543) Add the changes missing from #1535. (@groyoh)
- [#1535](https://github.com/rails-api/active_model_serializers/pull/1535) Move the adapter and adapter folder to
active_model_serializers folder and changes the module namespace. (@domitian @bf4)
- [#1497](https://github.com/rails-api/active_model_serializers/pull/1497) Add JRuby-9000 to appveyor.yml(@corainchicago)
- [#1420](https://github.com/rails-api/active_model_serializers/pull/1420) Adds tests and documentation for polymorphism(@marcgarreau)
### [v0.10.0.rc4 (2016-01-27)](https://github.com/rails-api/active_model_serializers/compare/v0.10.0.rc3...v0.10.0.rc4)
Breaking changes:
- [#1360](https://github.com/rails-api/active_model_serializers/pull/1360)
[#1369](https://github.com/rails-api/active_model_serializers/pull/1369) Drop support for Ruby 1.9.3 (@karaAJC, @maurogeorge)
- [#1131](https://github.com/rails-api/active_model_serializers/pull/1131) Remove Serializer#root_name (@beauby)
- [#1138](https://github.com/rails-api/active_model_serializers/pull/1138) Introduce Adapter::Base (@bf4)
* Adapters now inherit Adapter::Base. 'Adapter' is now a module, no longer a class.
* using a class as a namespace that you also inherit from is complicated and circular at times i.e.
buggy (see https://github.com/rails-api/active_model_serializers/pull/1177)
* The class methods on Adapter aren't necessarily related to the instance methods, they're more
Adapter functions.
* named `Base` because it's a Rails-ism.
* It helps to isolate and highlight what the Adapter interface actually is.
- [#1418](https://github.com/rails-api/active_model_serializers/pull/1418)
serialized collections now use the root option as is; now, only the
root derived from the serializer or object is always pluralized.
Features:
- [#1406](https://github.com/rails-api/active_model_serializers/pull/1406) Allow for custom dynamic values in JSON API links (@beauby)
- [#1270](https://github.com/rails-api/active_model_serializers/pull/1270) Adds `assert_response_schema` test helper (@maurogeorge)
- [#1099](https://github.com/rails-api/active_model_serializers/pull/1099) Adds `assert_serializer` test helper (@maurogeorge)
- [#1403](https://github.com/rails-api/active_model_serializers/pull/1403) Add support for if/unless on attributes/associations (@beauby)
- [#1248](https://github.com/rails-api/active_model_serializers/pull/1248) Experimental: Add support for JSON API deserialization (@beauby)
- [#1378](https://github.com/rails-api/active_model_serializers/pull/1378) Change association blocks
to be evaluated in *serializer* scope, rather than *association* scope. (@bf4)
* Syntax changes from e.g.
`has_many :titles do customers.pluck(:title) end` (in #1356) to
`has_many :titles do object.customers.pluck(:title) end`
- [#1356](https://github.com/rails-api/active_model_serializers/pull/1356) Add inline syntax for
attributes and associations (@bf4 @beauby @noahsilas)
* Allows defining attributes so that they don't conflict with existing methods. e.g. `attribute
:title do 'Mr. Topum Hat' end`
* Allows defining associations so that they don't conflict with existing methods. e.g. `has_many
:titles do customers.pluck(:title) end`
* Allows dynamic associations, as compared to compare to using
[`virtual_value`](https://github.com/rails-api/active_model_serializers/pull/1356#discussion_r47146466).
e.g. `has_many :reviews, virtual_value: [{ id: 1 }, { id: 2 }]`
* Removes dynamically defined methods on the serializer
- [#1336](https://github.com/rails-api/active_model_serializers/pull/1336) Added support for Grape >= 0.13, < 1.0 (@johnhamelink)
- [#1322](https://github.com/rails-api/active_model_serializers/pull/1322) Instrumenting rendering of resources (@bf4, @maurogeorge)
- [#1291](https://github.com/rails-api/active_model_serializers/pull/1291) Add logging (@maurogeorge)
- [#1272](https://github.com/rails-api/active_model_serializers/pull/1272) Add PORO serializable base class: ActiveModelSerializers::Model (@bf4)
- [#1255](https://github.com/rails-api/active_model_serializers/pull/1255) Make more class attributes inheritable (@bf4)
- [#1249](https://github.com/rails-api/active_model_serializers/pull/1249) Inheritance of serializer inheriting the cache configuration(@Rodrigora)
- [#1247](https://github.com/rails-api/active_model_serializers/pull/1247) Add support for toplevel JSON API links (@beauby)
- [#1246](https://github.com/rails-api/active_model_serializers/pull/1246) Add support for resource-level JSON API links (@beauby)
- [#1225](https://github.com/rails-api/active_model_serializers/pull/1225) Better serializer lookup, use nested serializer when it exists (@beauby)
- [#1213](https://github.com/rails-api/active_model_serializers/pull/1213) `type` directive for serializer to control type field with json-api adapter (@youroff)
- [#1172](https://github.com/rails-api/active_model_serializers/pull/1172) Better serializer registration, get more than just the first module (@bf4)
- [#1158](https://github.com/rails-api/active_model_serializers/pull/1158) Add support for wildcards in `include` option (@beauby)
- [#1127](https://github.com/rails-api/active_model_serializers/pull/1127) Add support for nested
associations for JSON and Attributes adapters via the `include` option (@NullVoxPopuli, @beauby).
- [#1050](https://github.com/rails-api/active_model_serializers/pull/1050) Add support for toplevel jsonapi member (@beauby, @bf4)
- [#1251](https://github.com/rails-api/active_model_serializers/pull/1251) Rename ArraySerializer to
CollectionSerializer for clarity, add ActiveModelSerializers.config.collection_serializer (@bf4)
- [#1295](https://github.com/rails-api/active_model_serializers/pull/1295) Add config `serializer_lookup_enabled` that,
when disabled, requires serializers to explicitly specified. (@trek)
Fixes:
- [#1352](https://github.com/rails-api/active_model_serializers/pull/1352) Fix generators; Isolate Rails-specifc code in Railties (@dgynn, @bf4)
- [#1384](https://github.com/rails-api/active_model_serializers/pull/1384)Fix database state leaking across tests (@bf4)
- [#1297](https://github.com/rails-api/active_model_serializers/pull/1297) Fix `fields` option to restrict relationships as well (@beauby)
- [#1239](https://github.com/rails-api/active_model_serializers/pull/1239) Fix duplicates in JSON API compound documents (@beauby)
- [#1214](https://github.com/rails-api/active_model_serializers/pull/1214) retrieve the key from the reflection options when building associations (@NullVoxPopuli, @hut8)
- [#1358](https://github.com/rails-api/active_model_serializers/pull/1358) Handle serializer file paths with spaces (@rwstauner, @bf4)
- [#1195](https://github.com/rails-api/active_model_serializers/pull/1195) Fix id override (@beauby)
- [#1185](https://github.com/rails-api/active_model_serializers/pull/1185) Fix options passing in Json and Attributes adapters (@beauby)
Misc:
- [#1383](https://github.com/rails-api/active_model_serializers/pull/1383) Simplify reflections handling (@beauby)
- [#1370](https://github.com/rails-api/active_model_serializers/pull/1370) Simplify attributes handling via a mixin (@beauby)
- [#1301](https://github.com/rails-api/active_model_serializers/pull/1301) Mapping JSON API spec / schema to AMS (@bf4)
- [#1271](https://github.com/rails-api/active_model_serializers/pull/1271) Handle no serializer source file to digest (@bf4)
- [#1260](https://github.com/rails-api/active_model_serializers/pull/1260) Serialization and Cache Documentation (@bf4)
- [#1259](https://github.com/rails-api/active_model_serializers/pull/1259) Add more info to CONTRIBUTING (@bf4)
- [#1233](https://github.com/rails-api/active_model_serializers/pull/1233) Top-level meta and meta_key options no longer handled at serializer level (@beauby)
- [#1232](https://github.com/rails-api/active_model_serializers/pull/1232) fields option no longer handled at serializer level (@beauby)
- [#1220](https://github.com/rails-api/active_model_serializers/pull/1220) Remove empty rubocop.rake (@maurogeorge)
- [#1178](https://github.com/rails-api/active_model_serializers/pull/1178) env CAPTURE_STDERR=false lets devs see hard failures (@bf4)
- [#1177](https://github.com/rails-api/active_model_serializers/pull/1177) Remove Adapter autoloads in favor of require (@bf4)
- [#1117](https://github.com/rails-api/active_model_serializers/pull/1117) FlattenJson adapter no longer inherits Json adapter, renamed to Attributes (@bf4)
- [#1171](https://github.com/rails-api/active_model_serializers/pull/1171) add require statements to top of file (@shicholas)
- [#1167](https://github.com/rails-api/active_model_serializers/pull/1167) Delegate Serializer.attributes to Serializer.attribute (@bf4)
- [#1174](https://github.com/rails-api/active_model_serializers/pull/1174) Consistently refer to the 'JSON API' and the 'JsonApi' adapter (@bf4)
- [#1173](https://github.com/rails-api/active_model_serializers/pull/1173) Comment private accessor warnings (@bf4)
- [#1166](https://github.com/rails-api/active_model_serializers/pull/1166) Prefer methods over instance variables (@bf4)
- [#1168](https://github.com/rails-api/active_model_serializers/pull/1168) Fix appveyor failure cache not being expired (@bf4)
- [#1161](https://github.com/rails-api/active_model_serializers/pull/1161) Remove duplicate test helper (@bf4)
- [#1360](https://github.com/rails-api/active_model_serializers/pull/1360) Update CI to test 2.2.2 -> 2.2.3 (@karaAJC)
- [#1371](https://github.com/rails-api/active_model_serializers/pull/1371) Refactor, update, create documentation (@bf4)
### [v0.10.0.rc3 (2015-09-16)](https://github.com/rails-api/active_model_serializers/compare/v0.10.0.rc2...v0.10.0.rc3)
- [#1129](https://github.com/rails-api/active_model_serializers/pull/1129) Remove SerializableResource.serialize in favor of `.new` (@bf4)
- [#1155](https://github.com/rails-api/active_model_serializers/pull/1155) Outside controller use tutorial (@CodedBeardedSignedTaylor)
- [#1154](https://github.com/rails-api/active_model_serializers/pull/1154) Rubocop fixes for issues introduced by #1089 (@NullVoxPopuli)
- [#1089](https://github.com/rails-api/active_model_serializers/pull/1089) Add ActiveModelSerializers.logger with default null device (@bf4)
- [#1109](https://github.com/rails-api/active_model_serializers/pull/1109) Make better use of Minitest's lifecycle (@bf4)
- [#1144](https://github.com/rails-api/active_model_serializers/pull/1144) Fix Markdown to adapters documentation (@bacarini)
- [#1121](https://github.com/rails-api/active_model_serializers/pull/1121) Refactor `add_links` in JSONAPI adapter. (@beauby)
- [#1150](https://github.com/rails-api/active_model_serializers/pull/1150) Remove legacy method accidentally reintroduced in #1017 (@beauby)
- [#1149](https://github.com/rails-api/active_model_serializers/pull/1149) Update README with nested included association example. (@mattmueller)
- [#1110](https://github.com/rails-api/active_model_serializers/pull/1110) Add lint tests for AR models (@beauby)
- [#1131](https://github.com/rails-api/active_model_serializers/pull/1131) Extended format for JSONAPI `include` option (@beauby)
* adds extended format for `include` option to JsonApi adapter
- [#1142](https://github.com/rails-api/active_model_serializers/pull/1142) Updating wording on cache expiry in README (@leighhalliday)
- [#1140](https://github.com/rails-api/active_model_serializers/pull/1140) Fix typo in fieldset exception (@lautis)
- [#1132](https://github.com/rails-api/active_model_serializers/pull/1132) Get rid of unnecessary instance variables, and implied dependencies. (@beauby)
- [#1139](https://github.com/rails-api/active_model_serializers/pull/1139) Documentation for serializing resources without render (@PericlesTheo)
- [#1017](https://github.com/rails-api/active_model_serializers/pull/1017) Make Adapters registerable so they are not namespace-constrained (@bf4)
- [#1120](https://github.com/rails-api/active_model_serializers/pull/1120) Add windows platform to loading sqlite3 (@Eric-Guo)
- [#1123](https://github.com/rails-api/active_model_serializers/pull/1123) Remove url options (@bacarini)
- [#1093](https://github.com/rails-api/active_model_serializers/pull/1093) Factor `with_adapter` + force cache clear before each test. (@beauby)
- [#1095](https://github.com/rails-api/active_model_serializers/pull/1095) Add documentation about configuration options. (@beauby)
- [#1069](https://github.com/rails-api/active_model_serializers/pull/1069) Add test coverage; account for no artifacts on CI (@bf4)
- [#1103](https://github.com/rails-api/active_model_serializers/pull/1103) Move `id` and `json_api_type` methods from `Serializer` to `JsonApi`. (@beauby)
- [#1106](https://github.com/rails-api/active_model_serializers/pull/1106) Add Style enforcer (via Rubocop) (@bf4)
- [#1079](https://github.com/rails-api/active_model_serializers/pull/1079) Add ArraySerializer#object like Serializer (@bf4)
- [#1096](https://github.com/rails-api/active_model_serializers/pull/1096) Fix definition of serializer attributes with multiple calls to `attri⦠(@beauby)
- [#1105](https://github.com/rails-api/active_model_serializers/pull/1105) Add ActiveRecord-backed fixtures. (@beauby)
- [#1108](https://github.com/rails-api/active_model_serializers/pull/1108) Better lint (@bf4)
- [#1102](https://github.com/rails-api/active_model_serializers/pull/1102) Remove remains of `embed` option. (@beauby)
- [#1090](https://github.com/rails-api/active_model_serializers/pull/1090) Clarify AMS dependencies (@bf4)
- [#1081](https://github.com/rails-api/active_model_serializers/pull/1081) Add configuration option to set resource type to singular/plural (@beauby)
- [#1067](https://github.com/rails-api/active_model_serializers/pull/1067) Fix warnings (@bf4)
- [#1066](https://github.com/rails-api/active_model_serializers/pull/1066) Adding appveyor to the project (@joaomdmoura, @Eric-Guo, @bf4)
- [#1071](https://github.com/rails-api/active_model_serializers/pull/1071) Make testing suite running and pass in Windows (@Eric-Guo, @bf4)
- [#1041](https://github.com/rails-api/active_model_serializers/pull/1041) Adding pagination links (@bacarini)
* adds support for `pagination links` at top level of JsonApi adapter
- [#1063](https://github.com/rails-api/active_model_serializers/pull/1063) Lead by example: lint PORO model (@bf4)
- [#1](https://github.com/rails-api/active_model_serializers/pull/1) Test caller line parsing and digesting (@bf4)
- [#1048](https://github.com/rails-api/active_model_serializers/pull/1048) Let FlattenJson adapter decide it doesn't include meta (@bf4)
- [#1060](https://github.com/rails-api/active_model_serializers/pull/1060) Update fragment cache to support namespaced objects (@aaronlerch)
- [#1052](https://github.com/rails-api/active_model_serializers/pull/1052) Use underscored json_root when serializing a collection (@whatthewhat)
- [#1051](https://github.com/rails-api/active_model_serializers/pull/1051) Fix some invalid JSON in docs (@tjschuck)
- [#1049](https://github.com/rails-api/active_model_serializers/pull/1049) Fix incorrect s/options = {}/options ||= {} (@bf4)
- [#1037](https://github.com/rails-api/active_model_serializers/pull/1037) allow for type attribute (@lanej)
- [#1034](https://github.com/rails-api/active_model_serializers/pull/1034) allow id attribute to be overriden (@lanej)
- [#1035](https://github.com/rails-api/active_model_serializers/pull/1035) Fixed Comments highlight (@artLopez)
- [#1031](https://github.com/rails-api/active_model_serializers/pull/1031) Disallow to define multiple associations at once (@bolshakov)
- [#1032](https://github.com/rails-api/active_model_serializers/pull/1032) Wrap railtie requirement with rescue (@elliotlarson)
- [#1026](https://github.com/rails-api/active_model_serializers/pull/1026) Bump Version Number to 0.10.0.rc2 (@jfelchner)
- [#985](https://github.com/rails-api/active_model_serializers/pull/985) Associations implementation refactoring (@bolshakov)
- [#954](https://github.com/rails-api/active_model_serializers/pull/954) Encapsulate serialization in ActiveModel::SerializableResource (@bf4)
- [#972](https://github.com/rails-api/active_model_serializers/pull/972) Capture app warnings on test run (@bf4)
- [#1019](https://github.com/rails-api/active_model_serializers/pull/1019) Improve README.md (@baojjeu)
- [#998](https://github.com/rails-api/active_model_serializers/pull/998) Changing root to model class name (@joaomdmoura)
- [#1006](https://github.com/rails-api/active_model_serializers/pull/1006) Fix adapter inflection bug for api -> API (@bf4)
- [#1016](https://github.com/rails-api/active_model_serializers/pull/1016) require rails/railtie before subclassing Rails::Railtie (@bf4)
- [#1013](https://github.com/rails-api/active_model_serializers/pull/1013) Root option with empty array support (@vyrak, @mareczek)
- [#994](https://github.com/rails-api/active_model_serializers/pull/994) Starting Docs structure (@joaomdmoura)
- [#1007](https://github.com/rails-api/active_model_serializers/pull/1007) Bug fix for ArraySerializer json_key (@jiajiawang)
- [#1003](https://github.com/rails-api/active_model_serializers/pull/1003) Fix transient test failures (@Rodrigora)
- [#996](https://github.com/rails-api/active_model_serializers/pull/996) Add linter for serializable resource (@bf4)
- [#990](https://github.com/rails-api/active_model_serializers/pull/990) Adding json-api meta test (@joaomdmoura)
- [#984](https://github.com/rails-api/active_model_serializers/pull/984) Add option "key" to serializer associations (@Rodrigora)
- [#982](https://github.com/rails-api/active_model_serializers/pull/982) Fix typo (@bf4)
- [#981](https://github.com/rails-api/active_model_serializers/pull/981) Remove unused PORO#to_param (@bf4)
- [#978](https://github.com/rails-api/active_model_serializers/pull/978) fix generators template bug (@regonn)
- [#975](https://github.com/rails-api/active_model_serializers/pull/975) Fixes virtual value not being used (@GriffinHeart)
- [#970](https://github.com/rails-api/active_model_serializers/pull/970) Fix transient tests failures (@Rodrigora)
- [#962](https://github.com/rails-api/active_model_serializers/pull/962) Rendering objects that doesn't have serializers (@bf4, @joaomdmoura, @JustinAiken)
- [#939](https://github.com/rails-api/active_model_serializers/pull/939) Use a more precise generated cache key (@aaronlerch)
- [#971](https://github.com/rails-api/active_model_serializers/pull/971) Restore has_one to generator (@bf4)
- [#965](https://github.com/rails-api/active_model_serializers/pull/965) options fedault valueserializable_hash and as_json (@bf4)
- [#959](https://github.com/rails-api/active_model_serializers/pull/959) TYPO on README.md (@kangkyu)
### [v0.10.0.rc2 (2015-06-16)](https://github.com/rails-api/active_model_serializers/compare/v0.10.0.rc1...v0.10.0.rc2)
- [#958](https://github.com/rails-api/active_model_serializers/pull/958) Splitting json adapter into two (@joaomdmoura)
* adds FlattenJSON as default adapter
- [#953](https://github.com/rails-api/active_model_serializers/pull/953) use model name to determine the type (@lsylvester)
* uses model name to determine the type
- [#949](https://github.com/rails-api/active_model_serializers/pull/949) Don't pass serializer option to associated serializers (@bf4, @edwardloveall)
- [#902](https://github.com/rails-api/active_model_serializers/pull/902) Added serializer file digest to the cache_key (@cristianbica)
- [#948](https://github.com/rails-api/active_model_serializers/pull/948) AMS supports JSONAPI 1.0 instead of RC4 (@SeyZ)
- [#936](https://github.com/rails-api/active_model_serializers/pull/936) Include meta when using json adapter with custom root (@chrisbranson)
- [#942](https://github.com/rails-api/active_model_serializers/pull/942) Small code styling issue (@thiagofm)
- [#930](https://github.com/rails-api/active_model_serializers/pull/930) Reverting PR #909 (@joaomdmoura)
- [#924](https://github.com/rails-api/active_model_serializers/pull/924) Avoid unecessary calls to attribute methods when fragment caching (@navinpeiris)
- [#925](https://github.com/rails-api/active_model_serializers/pull/925) Updates JSON API Adapter to generate RC4 schema (@benedikt)
* adds JSON API support 1.0
- [#918](https://github.com/rails-api/active_model_serializers/pull/918) Adding rescue_with_handler to clear state (@ryansch)
- [#909](https://github.com/rails-api/active_model_serializers/pull/909) Defining Json-API Adapter as Default (@joaomdmoura)
* remove root key option and split JSON adapter
- [#914](https://github.com/rails-api/active_model_serializers/pull/914) Prevent possible duplicated attributes in serializer (@groyoh)
- [#880](https://github.com/rails-api/active_model_serializers/pull/880) Inabling subclasses serializers to inherit attributes (@groyoh)
- [#913](https://github.com/rails-api/active_model_serializers/pull/913) Avoiding the serializer option when instantiating a new one for ArraySerializer Fixed #911 (@groyoh)
- [#897](https://github.com/rails-api/active_model_serializers/pull/897) Allow to define custom serializer for given class (@imanel)
- [#892](https://github.com/rails-api/active_model_serializers/pull/892) Fixed a bug that appeared when json adapter serialize a nil association (@groyoh)
- [#895](https://github.com/rails-api/active_model_serializers/pull/895) Adding a test to cover 'meta' and 'meta_key' attr_readers (@adomokos)
- [#894](https://github.com/rails-api/active_model_serializers/pull/894) Fixing typos in README.md (@adomokos)
- [#888](https://github.com/rails-api/active_model_serializers/pull/888) Changed duplicated test name in action controller test (@groyoh)
- [#890](https://github.com/rails-api/active_model_serializers/pull/890) Remove unused method `def_serializer` (@JustinAiken)
- [#887](https://github.com/rails-api/active_model_serializers/pull/887) Fixing tests on JRuby (@joaomdmoura)
- [#885](https://github.com/rails-api/active_model_serializers/pull/885) Updates rails versions for test and dev (@tonyta)
### [v0.10.0.rc1 (2015-04-22)](https://github.com/rails-api/active_model_serializers/compare/86fc7d7227f3ce538fcb28c1e8c7069ce311f0e1...v0.10.0.rc1)
- [#810](https://github.com/rails-api/active_model_serializers/pull/810) Adding Fragment Cache to AMS (@joaomdmoura)
* adds fragment cache support
- [#868](https://github.com/rails-api/active_model_serializers/pull/868) Fixed a bug that appears when a nil association is included (@groyoh)
- [#861](https://github.com/rails-api/active_model_serializers/pull/861) README: Add emphasis to single-word difference (@machty)
- [#858](https://github.com/rails-api/active_model_serializers/pull/858) Included resource fixes (@mateomurphy)
- [#853](https://github.com/rails-api/active_model_serializers/pull/853) RC3 Updates for JSON API (@mateomurphy)
- [#852](https://github.com/rails-api/active_model_serializers/pull/852) Fix options merge order in `each_association` (@mateomurphy)
- [#850](https://github.com/rails-api/active_model_serializers/pull/850) Use association value for determining serializer used (@mateomurphy)
- [#843](https://github.com/rails-api/active_model_serializers/pull/843) Remove the mailing list from the README (@JoshSmith)
- [#842](https://github.com/rails-api/active_model_serializers/pull/842) Add notes on how you can help to contributing documentation (@JoshSmith)
- [#833](https://github.com/rails-api/active_model_serializers/pull/833) Cache serializers for class (@lsylvester)
- [#837](https://github.com/rails-api/active_model_serializers/pull/837) Store options in array serializers (@kurko)
- [#836](https://github.com/rails-api/active_model_serializers/pull/836) Makes passed in options accessible inside serializers (@kurko)
- [#773](https://github.com/rails-api/active_model_serializers/pull/773) Make json api adapter 'include' option accept an array (@sweatypitts)
- [#830](https://github.com/rails-api/active_model_serializers/pull/830) Add contributing readme (@JoshSmith)
- [#811](https://github.com/rails-api/active_model_serializers/pull/811) Reimplement serialization scope and scope_name (@mateomurphy)
- [#725](https://github.com/rails-api/active_model_serializers/pull/725) Support has_one to be compatible with 0.8.x (@ggordon)
* adds `has_one` attribute for backwards compatibility
- [#822](https://github.com/rails-api/active_model_serializers/pull/822) Replace has_one with attribute in template (@bf4)
- [#821](https://github.com/rails-api/active_model_serializers/pull/821) Fix explicit serializer for associations (@wjordan)
- [#798](https://github.com/rails-api/active_model_serializers/pull/798) Fix lost test `test_include_multiple_posts_and_linked` (@donbobka)
- [#807](https://github.com/rails-api/active_model_serializers/pull/807) Add Overriding attribute methods section to README. (@alexstophel)
- [#693](https://github.com/rails-api/active_model_serializers/pull/693) Cache Support at AMS 0.10.0 (@joaomdmoura)
* adds cache support to attributes and associations.
- [#792](https://github.com/rails-api/active_model_serializers/pull/792) Association overrides (@kurko)
* adds method to override association
- [#794](https://github.com/rails-api/active_model_serializers/pull/794) add to_param for correct URL generation (@carlesjove)
### v0.10.0-pre
- [Introduce Adapter](https://github.com/rails-api/active_model_serializers/commit/f00fe5595ddf741dc26127ed8fe81adad833ead5)
- Prefer `ActiveModel::Serializer` to `ActiveModelSerializers`:
- [Namespace](https://github.com/rails-api/active_model_serializers/commit/729a823868e8c7ac86c653fcc7100ee511e08cb6#diff-fe7aa2941c19a41ccea6e52940d84016).
- [README](https://github.com/rails-api/active_model_serializers/commit/4a2d9853ba7486acc1747752982aa5650e7fd6e9).
## 0.09.x
### v0.9.3 (2015/01/21 20:29 +00:00)
Features:
- [#774](https://github.com/rails-api/active_model_serializers/pull/774) Fix nested include attributes (@nhocki)
- [#771](https://github.com/rails-api/active_model_serializers/pull/771) Make linked resource type names consistent with root names (@sweatypitts)
- [#696](https://github.com/rails-api/active_model_serializers/pull/696) Explicitly set serializer for associations (@ggordon)
- [#700](https://github.com/rails-api/active_model_serializers/pull/700) sparse fieldsets (@arenoir)
- [#768](https://github.com/rails-api/active_model_serializers/pull/768) Adds support for `meta` and `meta_key` attribute (@kurko)
### v0.9.1 (2014/12/04 11:54 +00:00)
- [#707](https://github.com/rails-api/active_model_serializers/pull/707) A Friendly Note on Which AMS Version to Use (@jherdman)
- [#730](https://github.com/rails-api/active_model_serializers/pull/730) Fixes nested has_many links in JSONAPI (@kurko)
- [#718](https://github.com/rails-api/active_model_serializers/pull/718) Allow overriding the adapter with render option (@ggordon)
- [#720](https://github.com/rails-api/active_model_serializers/pull/720) Rename attribute with :key (0.8.x compatibility) (@ggordon)
- [#728](https://github.com/rails-api/active_model_serializers/pull/728) Use type as key for linked resources (@kurko)
- [#729](https://github.com/rails-api/active_model_serializers/pull/729) Use the new beta build env on Travis (@joshk)
- [#703](https://github.com/rails-api/active_model_serializers/pull/703) Support serializer and each_serializer options in renderer (@ggordon, @mieko)
- [#727](https://github.com/rails-api/active_model_serializers/pull/727) Includes links inside of linked resources (@kurko)
- [#726](https://github.com/rails-api/active_model_serializers/pull/726) Bugfix: include nested has_many associations (@kurko)
- [#722](https://github.com/rails-api/active_model_serializers/pull/722) Fix infinite recursion (@ggordon)
- [#1](https://github.com/rails-api/active_model_serializers/pull/1) Allow for the implicit use of ArraySerializer when :each_serializer is specified (@mieko)
- [#692](https://github.com/rails-api/active_model_serializers/pull/692) Include 'linked' member for json-api collections (@ggordon)
- [#714](https://github.com/rails-api/active_model_serializers/pull/714) Define as_json instead of to_json (@guilleiguaran)
- [#710](https://github.com/rails-api/active_model_serializers/pull/710) JSON-API: Don't include linked section if associations are empty (@guilleiguaran)
- [#711](https://github.com/rails-api/active_model_serializers/pull/711) Fixes rbx gems bundling on TravisCI (@kurko)
- [#709](https://github.com/rails-api/active_model_serializers/pull/709) Add type key when association name is different than object type (@guilleiguaran)
- [#708](https://github.com/rails-api/active_model_serializers/pull/708) Handle correctly null associations (@guilleiguaran)
- [#691](https://github.com/rails-api/active_model_serializers/pull/691) Fix embed option for associations (@jacob-s-son)
- [#689](https://github.com/rails-api/active_model_serializers/pull/689) Fix support for custom root in JSON-API adapter (@guilleiguaran)
- [#685](https://github.com/rails-api/active_model_serializers/pull/685) Serialize ids as strings in JSON-API adapter (@guilleiguaran)
- [#684](https://github.com/rails-api/active_model_serializers/pull/684) Refactor adapters to implement support for array serialization (@guilleiguaran)
- [#682](https://github.com/rails-api/active_model_serializers/pull/682) Include root by default in JSON-API serializers (@guilleiguaran)
- [#625](https://github.com/rails-api/active_model_serializers/pull/625) Add DSL for urls (@JordanFaust)
- [#677](https://github.com/rails-api/active_model_serializers/pull/677) Add support for embed: :ids option for in associations (@guilleiguaran)
- [#681](https://github.com/rails-api/active_model_serializers/pull/681) Check superclasses for Serializers (@quainjn)
- [#680](https://github.com/rails-api/active_model_serializers/pull/680) Add support for root keys (@NullVoxPopuli)
- [#675](https://github.com/rails-api/active_model_serializers/pull/675) Support Rails 4.2.0 (@tricknotes)
- [#667](https://github.com/rails-api/active_model_serializers/pull/667) Require only activemodel instead of full rails (@guilleiguaran)
- [#653](https://github.com/rails-api/active_model_serializers/pull/653) Add "_test" suffix to JsonApi::HasManyTest filename. (@alexgenco)
- [#631](https://github.com/rails-api/active_model_serializers/pull/631) Update build badge URL (@craiglittle)
### 0.9.0.alpha1 - January 7, 2014
### 0.9.0.pre
* The following methods were removed
- Model#active\_model\_serializer
- Serializer#include!
- Serializer#include?
- Serializer#attr\_disabled=
- Serializer#cache
- Serializer#perform\_caching
- Serializer#schema (needs more discussion)
- Serializer#attribute
- Serializer#include\_#{name}? (filter method added)
- Serializer#attributes (took a hash)
* The following things were added
- Serializer#filter method
- CONFIG object
* Remove support for ruby 1.8 versions.
* Require rails >= 3.2.
* Serializers for associations are being looked up in a parent serializer's namespace first. Same with controllers' namespaces.
* Added a "prefix" option in case you want to use a different version of serializer.
* Serializers default namespace can be set in `default_serializer_options` and inherited by associations.
* [Beginning of rewrite: c65d387705ec534db171712671ba7fcda4f49f68](https://github.com/rails-api/active_model_serializers/commit/c65d387705ec534db171712671ba7fcda4f49f68)
## 0.08.x
### v0.8.3 (2014/12/10 14:45 +00:00)
- [#753](https://github.com/rails-api/active_model_serializers/pull/753) Test against Ruby 2.2 on Travis CI (@tricknotes)
- [#745](https://github.com/rails-api/active_model_serializers/pull/745) Missing a word (@jockee)
### v0.8.2 (2014/09/01 21:00 +00:00)
- [#612](https://github.com/rails-api/active_model_serializers/pull/612) Feature/adapter (@bolshakov)
* adds adapters pattern
- [#615](https://github.com/rails-api/active_model_serializers/pull/615) Rails does not support const_defined? in development mode (@tpitale)
- [#613](https://github.com/rails-api/active_model_serializers/pull/613) README: typo fix on attributes (@spk)
- [#614](https://github.com/rails-api/active_model_serializers/pull/614) Fix rails 4.0.x build. (@arthurnn)
- [#610](https://github.com/rails-api/active_model_serializers/pull/610) ArraySerializer (@bolshakov)
- [#607](https://github.com/rails-api/active_model_serializers/pull/607) ruby syntax highlights (@zigomir)
- [#602](https://github.com/rails-api/active_model_serializers/pull/602) Add DSL for associations (@JordanFaust)
### 0.8.1 (May 6, 2013)
* Fix bug whereby a serializer using 'options' would blow up.
### 0.8.0 (May 5, 2013)
* Attributes can now have optional types.
* A new DefaultSerializer ensures that POROs behave the same way as ActiveModels.
* If you wish to override ActiveRecord::Base#to_Json, you can now require
'active_record/serializer_override'. We don't recommend you do this, but
many users do, so we've left it optional.
* Fixed a bug where ActionController wouldn't always have MimeResponds.
* An optinal caching feature allows you to cache JSON & hashes that AMS uses.
Adding 'cached true' to your Serializers will turn on this cache.
* URL helpers used inside of Engines now work properly.
* Serializers now can filter attributes with `only` and `except`:
```
UserSerializer.new(user, only: [:first_name, :last_name])
UserSerializer.new(user, except: :first_name)
```
* Basic Mongoid support. We now include our mixins in the right place.
* On Ruby 1.8, we now generate an `id` method that properly serializes `id`
columns. See issue #127 for more.
* Add an alias for `scope` method to be the name of the context. By default
this is `current_user`. The name is automatically set when using
`serialization_scope` in the controller.
* Pass through serialization options (such as `:include`) when a model
has no serializer defined.
## [0.7.0 (March 6, 2013)](https://github.com/rails-api/active_model_serializers/commit/fabdc621ff97fbeca317f6301973dd4564b9e695)
* ```embed_key``` option to allow embedding by attributes other than IDs
* Fix rendering nil with custom serializer
* Fix global ```self.root = false```
* Add support for specifying the serializer for an association as a String
* Able to specify keys on the attributes method
* Serializer Reloading via ActiveSupport::DescendantsTracker
* Reduce double map to once; Fixes datamapper eager loading.
## 0.6.0 (October 22, 2012)
* Serialize sets properly
* Add root option to ArraySerializer
* Support polymorphic associations
* Support :each_serializer in ArraySerializer
* Add `scope` method to easily access the scope in the serializer
* Fix regression with Rails 3.2.6; add Rails 4 support
* Allow serialization_scope to be disabled with serialization_scope nil
* Array serializer should support pure ruby objects besides serializers
## 0.05.x
### [0.5.2 (June 5, 2012)](https://github.com/rails-api/active_model_serializers/commit/615afd125c260432d456dc8be845867cf87ea118#diff-0c5c12f311d3b54734fff06069efd2ac)
### [0.5.1 (May 23, 2012)](https://github.com/rails-api/active_model_serializers/commit/00194ec0e41831802fcbf893a34c0bb0853ebe14#diff-0c5c12f311d3b54734fff06069efd2ac)
### [0.5.0 (May 16, 2012)](https://github.com/rails-api/active_model_serializers/commit/33d4842dcd35c7167b0b33fc0abcf00fb2c92286)
* First tagged version
* Changes generators to always generate an ApplicationSerializer
## [0.1.0 (December 21, 2011)](https://github.com/rails-api/active_model_serializers/commit/1e0c9ef93b96c640381575dcd30be07ac946818b)
## First Commit as [Rails Serializers 0.0.1](https://github.com/rails-api/active_model_serializers/commit/d72b66d4c5355b0ff0a75a04895fcc4ea5b0c65e)
(December 1, 2011).
## Prehistory
- [Changing Serialization/Serializers namespace to `Serializable` (November 30, 2011)](https://github.com/rails/rails/commit/8896b4fdc8a543157cdf4dfc378607ebf6c10ab0)
- [Merge branch 'serializers'. This implements the ActiveModel::Serializer object. Includes code, tests, generators and guides. From JosƩ and Yehuda with love.](https://github.com/rails/rails/commit/fcacc6986ab60f1fb2e423a73bf47c7abd7b191d)
- But [was reverted](https://github.com/rails/rails/commit/5b2eb64ceb08cd005dc06b721935de5853971473).
'[Revert the serializers API as other alternatives are now also under discussion](https://github.com/rails/rails/commit/0a4035b12a6c59253cb60f9e3456513c6a6a9d33)'.
- [Proposed Implementation to Rails 3.2 by @wycats and @josevalim (November 25, 2011)](https://github.com/rails/rails/pull/3753)
- [Creation of `ActionController::Serialization`, initial serializer
support (September, 26 2011)](https://github.com/rails/rails/commit/8ff7693a8dc61f43fc4eaf72ed24d3b8699191fe).
- [Docs and CHANGELOG](https://github.com/rails/rails/commit/696d01f7f4a8ed787924a41cce6df836cd73c46f)
- [Deprecation of ActiveModel::Serialization to ActiveModel::Serializable](https://github.com/rails/rails/blob/696d01f7f4a8ed787924a41cce6df836cd73c46f/activemodel/lib/active_model/serialization.rb)
- [Creation of `ActiveModel::Serialization` from `ActiveModel::Serializer` in Rails (2009)](https://github.com/rails/rails/commit/c6bc8e662614be711f45a8d4b231d5f993b024a7#diff-d029b9768d8df0407a35804a468e3ae5)
- [Integration of `ActiveModel::Serializer` into `ActiveRecord::Serialization`](https://github.com/rails/rails/commit/783db25e0c640c1588732967a87d65c10fddc08e)
- [Creation of `ActiveModel::Serializer` in Rails (2009)](https://github.com/rails/rails/commit/d2b78b3594b9cc9870e6a6ebfeb2e56d00e6ddb8#diff-80d5beeced9bdc24ca2b04a201543bdd)
- [Creation of `ActiveModel::Serializers::JSON` in Rails (2009)](https://github.com/rails/rails/commit/fbdf706fffbfb17731a1f459203d242414ef5086)
active_model_serializers-0.10.10/CODE_OF_CONDUCT.md 0000664 0000000 0000000 00000006301 13512322311 0021510 0 ustar 00root root 0000000 0000000 # Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting one of the owners listed at https://rubygems.org/gems/active_model_serializers. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/ active_model_serializers-0.10.10/CONTRIBUTING.md 0000664 0000000 0000000 00000007444 13512322311 0021153 0 ustar 00root root 0000000 0000000 ## Have an issue?
Before opening an issue, try the following:
##### Consult the documentation
See if your issue can be resolved by information in the documentation.
- [0.10 (master) Documentation](https://github.com/rails-api/active_model_serializers/tree/master/docs)
- [](http://www.rubydoc.info/github/rails-api/active_model_serializers/v0.10.0)
- [Guides](docs)
- [0.9 (0-9-stable) Documentation](https://github.com/rails-api/active_model_serializers/tree/0-9-stable)
- [0.8 (0-8-stable) Documentation](https://github.com/rails-api/active_model_serializers/tree/0-8-stable)
##### Check for an existing issue
Take a look at the issues to see if a similar one has already been created. If
one exists, please add any additional information that might expedite
resolution.
#### Open an issue
If the documentation wasn't able to help resolve the issue and no issue already
exists, please open a new issue with the following in mind:
- Please make sure only to include one issue per report. If you encounter
multiple, unrelated issues, please report them as such.
- Be detailed. Provide backtraces and example code when possible. Provide
information about your environment. e.g., Ruby version, rails version, etc.
- Own your issue. Actively participate in the discussion and help drive the
issue to closure.
- If you resolve your own issue, please share the details on the issue and close
it out. Others might have the same issue and sharing solutions is helpful.
## Contributing
Contributing can be done in many ways and is not exclusive to code. If you have
thoughts on a particular issue or feature, we encourage you to open new issues
for discussion or add your comments to existing ones.
#### Pull requests
We also gladly welcome pull requests. When preparing to work on pull request,
please adhere to these standards:
- Base work on the master branch unless fixing an issue with
[0.9-stable](https://github.com/rails-api/active_model_serializers/tree/0-9-stable)
or
[0.8-stable](https://github.com/rails-api/active_model_serializers/tree/0-8-stable)
- Squash your commits and regularly rebase off master.
- Provide a description of the changes contained in the pull request.
- Note any specific areas that should be reviewed.
- Include tests.
- The test suite must pass on [supported Ruby versions](.travis.yml)
- Include updates to the [documentation](https://github.com/rails-api/active_model_serializers/tree/master/docs)
where applicable.
- Update the
[CHANGELOG](https://github.com/rails-api/active_model_serializers/blob/master/CHANGELOG.md)
to the appropriate sections with a brief description of the changes.
- Do not change the VERSION file.
#### Running tests
Run all tests
`$ rake test`
Run a single test suite
`$ rake test TEST=path/to/test.rb`
Run a single test
`$ rake test TEST=path/to/test.rb TESTOPTS="--name=test_something"`
Run tests against different Rails versions by setting the RAILS_VERSION variable
and bundling gems. (save this script somewhere executable and run from top of AMS repository)
```bash
#!/usr/bin/env bash
rcommand='puts YAML.load_file("./.travis.yml")["env"]["matrix"].join(" ").gsub("RAILS_VERSION=", "")'
versions=$(ruby -ryaml -e "$rcommand")
for version in ${versions[@]}; do
export RAILS_VERSION="$version"
rm -f Gemfile.lock
bundle check || bundle --local || bundle
bundle exec rake test
if [ "$?" -eq 0 ]; then
# green in ANSI
echo -e "\033[32m **** Tests passed against Rails ${RAILS_VERSION} **** \033[0m"
else
# red in ANSI
echo -e "\033[31m **** Tests failed against Rails ${RAILS_VERSION} **** \033[0m"
read -p '[Enter] any key to continue, [q] to quit...' prompt
if [ "$prompt" = 'q' ]; then
unset RAILS_VERSION
exit 1
fi
fi
unset RAILS_VERSION
done
```
active_model_serializers-0.10.10/Gemfile 0000664 0000000 0000000 00000004451 13512322311 0020210 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
source 'https://rubygems.org'
#
# Add a Gemfile.local to locally bundle gems outside of version control
local_gemfile = File.join(File.expand_path('..', __FILE__), 'Gemfile.local')
eval_gemfile local_gemfile if File.readable?(local_gemfile)
# Specify your gem's dependencies in active_model_serializers.gemspec
gemspec
version = ENV['RAILS_VERSION'] || '4.2'
if version == 'master'
gem 'rack', github: 'rack/rack'
gem 'arel', github: 'rails/arel'
gem 'rails', github: 'rails/rails'
git 'https://github.com/rails/rails.git' do
gem 'railties'
gem 'activesupport'
gem 'activemodel'
gem 'actionpack'
gem 'activerecord', group: :test
# Rails 5
gem 'actionview'
end
else
gem_version = "~> #{version}.0"
gem 'rails', gem_version
gem 'railties', gem_version
gem 'activesupport', gem_version
gem 'activemodel', gem_version
gem 'actionpack', gem_version
gem 'activerecord', gem_version, group: :test
end
# https://github.com/bundler/bundler/blob/89a8778c19269561926cea172acdcda241d26d23/lib/bundler/dependency.rb#L30-L54
@windows_platforms = [:mswin, :mingw, :x64_mingw]
# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: (@windows_platforms + [:jruby])
if ENV['CI']
if RUBY_VERSION < '2.4'
# Windows: An error occurred while installing nokogiri (1.8.0)
gem 'nokogiri', '< 1.7', platforms: @windows_platforms
end
end
group :bench do
# https://github.com/rails-api/active_model_serializers/commit/cb4459580a6f4f37f629bf3185a5224c8624ca76
gem 'benchmark-ips', '>= 2.7.2', require: false, group: :development
end
group :test do
platforms(*(@windows_platforms + [:ruby])) do
if version == 'master' || version >= '6'
gem 'sqlite3', '~> 1.4'
else
gem 'sqlite3', '~> 1.3.13'
end
end
platforms :jruby do
if version == 'master' || version >= '5'
gem 'activerecord-jdbcsqlite3-adapter', '~> 50'
else
gem 'activerecord-jdbcsqlite3-adapter', '~> 1.3.0'
end
end
gem 'codeclimate-test-reporter', require: false
gem 'm', '~> 1.5'
gem 'pry', '>= 0.10'
gem 'byebug', '~> 8.2' if RUBY_VERSION < '2.2'
gem 'pry-byebug', platforms: :ruby
end
group :development, :test do
gem 'rubocop', '~> 0.40.0', require: false
gem 'yard', require: false
end
active_model_serializers-0.10.10/MIT-LICENSE 0000664 0000000 0000000 00000002056 13512322311 0020350 0 ustar 00root root 0000000 0000000 Copyright (c) 2014 Steve Klabnik
MIT License
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
active_model_serializers-0.10.10/README.md 0000664 0000000 0000000 00000031325 13512322311 0020174 0 ustar 00root root 0000000 0000000 # ActiveModelSerializers
Build Status |
|
Code Quality |
|
Issue Stats |
Pulse
|
## About
ActiveModelSerializers brings convention over configuration to your JSON generation.
ActiveModelSerializers works through two components: **serializers** and **adapters**.
Serializers describe _which_ attributes and relationships should be serialized.
Adapters describe _how_ attributes and relationships should be serialized.
SerializableResource co-ordinates the resource, Adapter and Serializer to produce the
resource serialization. The serialization has the `#as_json`, `#to_json` and `#serializable_hash`
methods used by the Rails JSON Renderer. (SerializableResource actually delegates
these methods to the adapter.)
By default ActiveModelSerializers will use the **Attributes Adapter** (no JSON root).
But we strongly advise you to use **JsonApi Adapter**, which
follows 1.0 of the format specified in [jsonapi.org/format](http://jsonapi.org/format).
Check how to change the adapter in the sections below.
`0.10.x` is **not** backward compatible with `0.9.x` nor `0.8.x`.
`0.10.x` is based on the `0.8.0` code, but with a more flexible
architecture. We'd love your help. [Learn how you can help here.](CONTRIBUTING.md)
## Installation
Add this line to your application's Gemfile:
```
gem 'active_model_serializers', '~> 0.10.0'
```
And then execute:
```
$ bundle
```
## Getting Started
See [Getting Started](docs/general/getting_started.md) for the nuts and bolts.
More information is available in the [Guides](docs) and
[High-level behavior](README.md#high-level-behavior).
## Getting Help
If you find a bug, please report an [Issue](https://github.com/rails-api/active_model_serializers/issues/new)
and see our [contributing guide](CONTRIBUTING.md).
If you have a question, please [post to Stack Overflow](http://stackoverflow.com/questions/tagged/active-model-serializers).
If you'd like to chat, we have a [community slack](http://amserializers.herokuapp.com).
Thanks!
## Documentation
If you're reading this at https://github.com/rails-api/active_model_serializers you are
reading documentation for our `master`, which may include features that have not
been released yet. Please see below for the documentation relevant to you.
- [0.10 (master) Documentation](https://github.com/rails-api/active_model_serializers/tree/master)
- [0.10.6 (latest release) Documentation](https://github.com/rails-api/active_model_serializers/tree/v0.10.6)
- [](http://www.rubydoc.info/gems/active_model_serializers/0.10.6)
- [Guides](docs)
- [0.9 (0-9-stable) Documentation](https://github.com/rails-api/active_model_serializers/tree/0-9-stable)
- [](http://www.rubydoc.info/github/rails-api/active_model_serializers/0-9-stable)
- [0.8 (0-8-stable) Documentation](https://github.com/rails-api/active_model_serializers/tree/0-8-stable)
- [](http://www.rubydoc.info/github/rails-api/active_model_serializers/0-8-stable)
## High-level behavior
Choose an adapter from [adapters](lib/active_model_serializers/adapter):
``` ruby
ActiveModelSerializers.config.adapter = :json_api # Default: `:attributes`
```
Given a [serializable model](lib/active_model/serializer/lint.rb):
```ruby
# either
class SomeResource < ActiveRecord::Base
# columns: title, body
end
# or
class SomeResource < ActiveModelSerializers::Model
attributes :title, :body
end
```
And initialized as:
```ruby
resource = SomeResource.new(title: 'ActiveModelSerializers', body: 'Convention over configuration')
```
Given a serializer for the serializable model:
```ruby
class SomeSerializer < ActiveModel::Serializer
attribute :title, key: :name
attributes :body
end
```
The model can be serialized as:
```ruby
options = {}
serialization = ActiveModelSerializers::SerializableResource.new(resource, options)
serialization.to_json
serialization.as_json
```
SerializableResource delegates to the adapter, which it builds as:
```ruby
adapter_options = {}
adapter = ActiveModelSerializers::Adapter.create(serializer, adapter_options)
adapter.to_json
adapter.as_json
adapter.serializable_hash
```
The adapter formats the serializer's attributes and associations (a.k.a. includes):
```ruby
serializer_options = {}
serializer = SomeSerializer.new(resource, serializer_options)
serializer.attributes
serializer.associations
```
## Architecture
This section focuses on architecture the 0.10.x version of ActiveModelSerializers. If you are interested in the architecture of the 0.8 or 0.9 versions,
please refer to the [0.8 README](https://github.com/rails-api/active_model_serializers/blob/0-8-stable/README.md) or
[0.9 README](https://github.com/rails-api/active_model_serializers/blob/0-9-stable/README.md).
The original design is also available [here](https://github.com/rails-api/active_model_serializers/blob/d72b66d4c5355b0ff0a75a04895fcc4ea5b0c65e/README.textile).
### ActiveModel::Serializer
An **`ActiveModel::Serializer`** wraps a [serializable resource](https://github.com/rails/rails/blob/4-2-stable/activemodel/lib/active_model/serialization.rb)
and exposes an `attributes` method, among a few others.
It allows you to specify which attributes and associations should be represented in the serializatation of the resource.
It requires an adapter to transform its attributes into a JSON document; it cannot be serialized itself.
It may be useful to think of it as a
[presenter](http://blog.steveklabnik.com/posts/2011-09-09-better-ruby-presenters).
#### ActiveModel::CollectionSerializer
The **`ActiveModel::CollectionSerializer`** represents a collection of resources as serializers
and, if there is no serializer, primitives.
### ActiveModelSerializers::Adapter::Base
The **`ActiveModelSerializers::Adapter::Base`** describes the structure of the JSON document generated from a
serializer. For example, the `Attributes` example represents each serializer as its
unmodified attributes. The `JsonApi` adapter represents the serializer as a [JSON
API](http://jsonapi.org/) document.
### ActiveModelSerializers::SerializableResource
The **`ActiveModelSerializers::SerializableResource`** acts to coordinate the serializer(s) and adapter
to an object that responds to `to_json`, and `as_json`. It is used in the controller to
encapsulate the serialization resource when rendered. However, it can also be used on its own
to serialize a resource outside of a controller, as well.
### Primitive handling
Definitions: A primitive is usually a String or Array. There is no serializer
defined for them; they will be serialized when the resource is converted to JSON (`as_json` or
`to_json`). (The below also applies for any object with no serializer.)
- ActiveModelSerializers doesn't handle primitives passed to `render json:` at all.
Internally, if no serializer can be found in the controller, the resource is not decorated by
ActiveModelSerializers.
- However, when a primitive value is an attribute or in a collection, it is not modified.
When serializing a collection and the collection serializer (CollectionSerializer) cannot
identify a serializer for a resource in its collection, it throws [`:no_serializer`](https://github.com/rails-api/active_model_serializers/issues/1191#issuecomment-142327128).
For example, when caught by `Reflection#build_association`, and the association value is set directly:
```ruby
reflection_options[:virtual_value] = association_value.try(:as_json) || association_value
```
(which is called by the adapter as `serializer.associations(*)`.)
### How options are parsed
High-level overview:
- For a **collection**
- `:serializer` specifies the collection serializer and
- `:each_serializer` specifies the serializer for each resource in the collection.
- For a **single resource**, the `:serializer` option is the resource serializer.
- Options are partitioned in serializer options and adapter options. Keys for adapter options are specified by
[`ADAPTER_OPTION_KEYS`](https://github.com/rails-api/active_model_serializers/blob/master/lib/active_model_serializers/serializable_resource.rb#L5).
The remaining options are serializer options.
Details:
1. **ActionController::Serialization**
1. `serializable_resource = ActiveModelSerializers::SerializableResource.new(resource, options)`
1. `options` are partitioned into `adapter_opts` and everything else (`serializer_opts`).
The `adapter_opts` keys are defined in [`ActiveModelSerializers::SerializableResource::ADAPTER_OPTION_KEYS`](lib/active_model_serializers/serializable_resource.rb#L5).
1. **ActiveModelSerializers::SerializableResource**
1. `if serializable_resource.serializer?` (there is a serializer for the resource, and an adapter is used.)
- Where `serializer?` is `use_adapter? && !!(serializer)`
- Where `use_adapter?`: 'True when no explicit adapter given, or explicit value is truthy (non-nil);
False when explicit adapter is falsy (nil or false)'
- Where `serializer`:
1. from explicit `:serializer` option, else
2. implicitly from resource `ActiveModel::Serializer.serializer_for(resource)`
1. A side-effect of checking `serializer` is:
- The `:serializer` option is removed from the serializer_opts hash
- If the `:each_serializer` option is present, it is removed from the serializer_opts hash and set as the `:serializer` option
1. The serializer and adapter are created as
1. `serializer_instance = serializer.new(resource, serializer_opts)`
2. `adapter_instance = ActiveModel::Serializer::Adapter.create(serializer_instance, adapter_opts)`
1. **ActiveModel::Serializer::CollectionSerializer#new**
1. If the `serializer_instance` was a `CollectionSerializer` and the `:serializer` serializer_opts
is present, then [that serializer is passed into each resource](https://github.com/rails-api/active_model_serializers/blob/a54d237e2828fe6bab1ea5dfe6360d4ecc8214cd/lib/active_model/serializer/array_serializer.rb#L14-L16).
1. **ActiveModel::Serializer#attributes** is used by the adapter to get the attributes for
resource as defined by the serializer.
(In Rails, the `options` are also passed to the `as_json(options)` or `to_json(options)`
methods on the resource serialization by the Rails JSON renderer. They are, therefore, important
to know about, but not part of ActiveModelSerializers.)
### What does a 'serializable resource' look like?
- An `ActiveRecord::Base` object.
- Any Ruby object that passes the
[Lint](https://www.rubydoc.info/gems/active_model_serializers/ActiveModel/Serializer/Lint/Tests)
[(code)](lib/active_model/serializer/lint.rb).
ActiveModelSerializers provides a
[`ActiveModelSerializers::Model`](https://github.com/rails-api/active_model_serializers/blob/master/lib/active_model_serializers/model.rb),
which is a simple serializable PORO (Plain-Old Ruby Object).
`ActiveModelSerializers::Model` may be used either as a reference implementation, or in production code.
```ruby
class MyModel < ActiveModelSerializers::Model
attributes :id, :name, :level
end
```
The default serializer for `MyModel` would be `MyModelSerializer` whether MyModel is an
ActiveRecord::Base object or not.
Outside of the controller the rules are **exactly** the same as for records. For example:
```ruby
render json: MyModel.new(level: 'awesome'), adapter: :json
```
would be serialized the same as
```ruby
ActiveModelSerializers::SerializableResource.new(MyModel.new(level: 'awesome'), adapter: :json).as_json
```
## Semantic Versioning
This project adheres to [semver](http://semver.org/)
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md)
active_model_serializers-0.10.10/Rakefile 0000664 0000000 0000000 00000003756 13512322311 0020371 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
begin
require 'bundler/setup'
rescue LoadError
puts 'You must `gem install bundler` and `bundle install` to run rake tasks'
end
begin
require 'simplecov'
rescue LoadError # rubocop:disable Lint/HandleExceptions
end
import('lib/tasks/rubocop.rake')
Bundler::GemHelper.install_tasks
require 'yard'
namespace :yard do
YARD::Rake::YardocTask.new(:doc) do |t|
t.stats_options = ['--list-undoc']
end
desc 'start a gem server'
task :server do
sh 'bundle exec yard server --gems'
end
desc 'use Graphviz to generate dot graph'
task :graph do
output_file = 'doc/erd.dot'
sh "bundle exec yard graph --protected --full --dependencies > #{output_file}"
puts 'open doc/erd.dot if you have graphviz installed'
end
end
require 'rake/testtask'
Rake::TestTask.new(:test) do |t|
t.libs << 'lib'
t.libs << 'test'
t.pattern = 'test/**/*_test.rb'
t.ruby_opts = ['-r./test/test_helper.rb']
t.ruby_opts << ' -w' unless ENV['NO_WARN'] == 'true'
t.verbose = true
end
desc 'Run isolated tests'
task isolated: ['test:isolated']
namespace :test do
task :isolated do
desc 'Run isolated tests for Railtie'
require 'shellwords'
dir = File.dirname(__FILE__)
dir = Shellwords.shellescape(dir)
isolated_test_files = FileList['test/**/*_test_isolated.rb']
# https://github.com/rails/rails/blob/3d590add45/railties/lib/rails/generators/app_base.rb#L345-L363
_bundle_command = Gem.bin_path('bundler', 'bundle')
require 'bundler'
Bundler.with_clean_env do
isolated_test_files.all? do |test_file|
command = "-w -I#{dir}/lib -I#{dir}/test #{Shellwords.shellescape(test_file)}"
full_command = %("#{Gem.ruby}" #{command})
system(full_command)
end or fail 'Failures' # rubocop:disable Style/AndOr
end
end
end
if ENV['RAILS_VERSION'].to_s > '4.0' && RUBY_ENGINE == 'ruby'
task default: [:isolated, :test, :rubocop]
else
task default: [:test, :rubocop]
end
desc 'CI test task'
task ci: [:default]
active_model_serializers-0.10.10/active_model_serializers.gemspec 0000664 0000000 0000000 00000004376 13512322311 0025337 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'active_model/serializer/version'
Gem::Specification.new do |spec|
spec.name = 'active_model_serializers'
spec.version = ActiveModel::Serializer::VERSION
spec.platform = Gem::Platform::RUBY
spec.authors = ['Steve Klabnik']
spec.email = ['steve@steveklabnik.com']
spec.summary = 'Conventions-based JSON generation for Rails.'
spec.description = 'ActiveModel::Serializers allows you to generate your JSON in an object-oriented and convention-driven manner.'
spec.homepage = 'https://github.com/rails-api/active_model_serializers'
spec.license = 'MIT'
spec.files = Dir["CHANGELOG.md", "MIT-LICENSE", "README.md", "lib/**/*"]
spec.require_paths = ['lib']
spec.executables = []
spec.required_ruby_version = '>= 2.1'
rails_versions = ['>= 4.1', '< 6.1']
spec.add_runtime_dependency 'activemodel', rails_versions
# 'activesupport', rails_versions
# 'builder'
spec.add_runtime_dependency 'actionpack', rails_versions
# 'activesupport', rails_versions
# 'rack'
# 'rack-test', '~> 0.6.2'
spec.add_development_dependency 'railties', rails_versions
# 'activesupport', rails_versions
# 'actionpack', rails_versions
# 'rake', '>= 0.8.7'
# 'activesupport', rails_versions
# 'i18n,
# 'tzinfo'
spec.add_development_dependency 'minitest', ['~> 5.0', '< 5.11']
# 'thread_safe'
spec.add_runtime_dependency 'jsonapi-renderer', ['>= 0.1.1.beta1', '< 0.3']
spec.add_runtime_dependency 'case_transform', '>= 0.2'
spec.add_development_dependency 'activerecord', rails_versions
# arel
# activesupport
# activemodel
# Soft dependency for pagination
spec.add_development_dependency 'kaminari', ' ~> 0.16.3'
spec.add_development_dependency 'will_paginate', '~> 3.0', '>= 3.0.7'
spec.add_development_dependency 'bundler', '~> 1.6'
spec.add_development_dependency 'simplecov', '~> 0.11'
spec.add_development_dependency 'timecop', '~> 0.7'
spec.add_development_dependency 'grape', ['>= 0.13', '< 0.19.1']
spec.add_development_dependency 'json_schema'
spec.add_development_dependency 'rake', ['>= 10.0', '< 12.0']
end
active_model_serializers-0.10.10/appveyor.yml 0000664 0000000 0000000 00000001121 13512322311 0021274 0 ustar 00root root 0000000 0000000 version: 1.0.{build}-{branch}
skip_tags: true
environment:
JRUBY_OPTS: "--dev -J-Xmx1024M --debug"
RAILS_VERSION: 5.2
matrix:
- ruby_version: "Ruby23"
- ruby_version: "Ruby23-x64"
cache:
- vendor/bundle
install:
- SET PATH=C:\%ruby_version%\bin;%PATH%
- gem uninstall bundler -a -x -I
- gem update --system 2.7.9
- # gem install bundler -v '1.17.3'
- bundle env
- bundle check || bundle install --path=vendor/bundle --retry=3 --jobs=3
- bundle clean --force
before_test:
- ruby -v
- gem -v
- bundle -v
test_script:
- bundle exec rake ci
build: off
active_model_serializers-0.10.10/bin/ 0000775 0000000 0000000 00000000000 13512322311 0017461 5 ustar 00root root 0000000 0000000 active_model_serializers-0.10.10/bin/bench 0000775 0000000 0000000 00000011774 13512322311 0020500 0 ustar 00root root 0000000 0000000 #!/usr/bin/env ruby
# ActiveModelSerializers Benchmark driver
# Adapted from
# https://github.com/ruby-bench/ruby-bench-suite/blob/8ad567f7e43a044ae48c36833218423bb1e2bd9d/rails/benchmarks/driver.rb
require 'bundler'
Bundler.setup
require 'json'
require 'pathname'
require 'optparse'
require 'digest'
require 'pathname'
require 'shellwords'
require 'logger'
require 'English'
class BenchmarkDriver
ROOT = Pathname File.expand_path(File.join('..', '..'), __FILE__)
BASE = ENV.fetch('BASE') { ROOT.join('test', 'benchmark') }
ESCAPED_BASE = Shellwords.shellescape(BASE)
def self.benchmark(options)
new(options).run
end
def self.parse_argv_and_run(argv = ARGV, options = {})
options = {
repeat_count: 1,
pattern: [],
env: 'CACHE_ON=on'
}.merge!(options)
OptionParser.new do |opts|
opts.banner = 'Usage: bin/bench [options]'
opts.on('-r', '--repeat-count [NUM]', 'Run benchmarks [NUM] times taking the best result') do |value|
options[:repeat_count] = value.to_i
end
opts.on('-p', '--pattern ', 'Benchmark name pattern') do |value|
options[:pattern] = value.split(',')
end
opts.on('-e', '--env ', 'ENV variables to pass in') do |value|
options[:env] = value.split(',')
end
end.parse!(argv)
benchmark(options)
end
attr_reader :commit_hash, :base
# Based on logfmt:
# https://www.brandur.org/logfmt
# For more complete implementation see:
# see https://github.com/arachnid-cb/logfmtr/blob/master/lib/logfmtr/base.rb
# For usage see:
# https://blog.codeship.com/logfmt-a-log-format-thats-easy-to-read-and-write/
# https://engineering.heroku.com/blogs/2014-09-05-hutils-explore-your-structured-data-logs/
# For Ruby parser see:
# https://github.com/cyberdelia/logfmt-ruby
def self.summary_logger(device = 'output.txt')
require 'time'
logger = Logger.new(device)
logger.level = Logger::INFO
logger.formatter = proc { |severity, datetime, progname, msg|
msg = "'#{msg}'"
"level=#{severity} time=#{datetime.utc.iso8601(6)} pid=#{Process.pid} progname=#{progname} msg=#{msg}#{$INPUT_RECORD_SEPARATOR}"
}
logger
end
def self.stdout_logger
logger = Logger.new(STDOUT)
logger.level = Logger::INFO
logger.formatter = proc { |_, _, _, msg| "#{msg}#{$INPUT_RECORD_SEPARATOR}" }
logger
end
def initialize(options)
@writer = ENV['SUMMARIZE'] ? self.class.summary_logger : self.class.stdout_logger
@repeat_count = options[:repeat_count]
@pattern = options[:pattern]
@commit_hash = options.fetch(:commit_hash) { `git rev-parse --short HEAD`.chomp }
@base = options.fetch(:base) { ESCAPED_BASE }
@env = Array(options[:env]).join(' ')
@rubyopt = options[:rubyopt] # TODO: rename
end
def run
files.each do |path|
next if !@pattern.empty? && /#{@pattern.join('|')}/ !~ File.basename(path)
run_single(Shellwords.shellescape(path))
end
end
private
def files
Dir[File.join(base, 'bm_*')]
end
def run_single(path)
script = "RAILS_ENV=production #{@env} ruby #{@rubyopt} #{path}"
environment = `ruby -v`.chomp.strip[/\d+\.\d+\.\d+\w+/]
runs_output = measure(script)
if runs_output.empty?
results = { error: :no_results }
return
end
results = {}
results['commit_hash'] = commit_hash
results['version'] = runs_output.first['version']
results['rails_version'] = runs_output.first['rails_version']
results['benchmark_run[environment]'] = environment
results['runs'] = []
runs_output.each do |output|
results['runs'] << {
'benchmark_type[category]' => output['label'],
'benchmark_run[result][iterations_per_second]' => output['iterations_per_second'].round(3),
'benchmark_run[result][total_allocated_objects_per_iteration]' => output['total_allocated_objects_per_iteration']
}
end
ensure
results && report(results)
end
def report(results)
@writer.info { 'Benchmark results:' }
@writer.info { JSON.pretty_generate(results) }
end
def summarize(result)
puts "#{result['label']} #{result['iterations_per_second']}/ips; #{result['total_allocated_objects_per_iteration']} objects"
end
# FIXME: ` provides the full output but it'll return failed output as well.
def measure(script)
results = Hash.new { |h, k| h[k] = [] }
@repeat_count.times do
output = sh(script)
output.each_line do |line|
next if line.nil?
begin
result = JSON.parse(line)
rescue JSON::ParserError
result = { error: line } # rubocop:disable Lint/UselessAssignment
else
summarize(result)
results[result['label']] << result
end
end
end
results.map do |_, bm_runs|
bm_runs.sort_by do |run|
run['iterations_per_second']
end.last
end
end
def sh(cmd)
`#{cmd}`
end
end
BenchmarkDriver.parse_argv_and_run if $PROGRAM_NAME == __FILE__
active_model_serializers-0.10.10/bin/bench_regression 0000775 0000000 0000000 00000020667 13512322311 0022741 0 ustar 00root root 0000000 0000000 #!/usr/bin/env ruby
require 'fileutils'
require 'pathname'
require 'shellwords'
require 'English'
############################
# USAGE
#
# bundle exec bin/bench_regression
# defaults to the current branch
# defaults to the master branch
# bundle exec bin/bench_regression current # will run on the current branch
# bundle exec bin/bench_regression revisions 792fb8a90 master # every revision inclusive
# bundle exec bin/bench_regression 792fb8a90 master --repeat-count 2 --env CACHE_ON=off
# bundle exec bin/bench_regression vendor
###########################
class BenchRegression
ROOT = Pathname File.expand_path(File.join(*['..', '..']), __FILE__)
TMP_DIR_NAME = File.join('tmp', 'bench')
TMP_DIR = File.join(ROOT, TMP_DIR_NAME)
E_TMP_DIR = Shellwords.shellescape(TMP_DIR)
load ROOT.join('bin', 'bench')
attr_reader :source_stasher
def initialize
@source_stasher = SourceStasher.new
end
class SourceStasher
attr_reader :gem_require_paths, :gem_paths
attr_writer :vendor
def initialize
@gem_require_paths = []
@gem_paths = []
refresh_temp_dir
@vendor = false
end
def temp_dir_empty?
File.directory?(TMP_DIR) &&
Dir[File.join(TMP_DIR, '*')].none?
end
def empty_temp_dir
return if @vendor
return if temp_dir_empty?
FileUtils.mkdir_p(TMP_DIR)
Dir[File.join(TMP_DIR, '*')].each do |file|
if File.directory?(file)
FileUtils.rm_rf(file)
else
FileUtils.rm(file)
end
end
end
def fill_temp_dir
vendor_files(Dir[File.join(ROOT, 'test', 'benchmark', '*.{rb,ru}')])
# vendor_file(File.join('bin', 'bench'))
housekeeping { empty_temp_dir }
vendor_gem('benchmark-ips')
end
def vendor_files(files)
files.each do |file|
vendor_file(file)
end
end
def vendor_file(file)
FileUtils.cp(file, File.join(TMP_DIR, File.basename(file)))
end
def vendor_gem(gem_name)
directory_name = `bundle exec gem unpack benchmark-ips --target=#{E_TMP_DIR}`[/benchmark-ips.+\d/]
gem_paths << File.join(TMP_DIR, directory_name)
gem_require_paths << File.join(TMP_DIR_NAME, directory_name, 'lib')
housekeeping { remove_vendored_gems }
end
def remove_vendored_gems
return if @vendor
FileUtils.rm_rf(*gem_paths)
end
def refresh_temp_dir
empty_temp_dir
fill_temp_dir
end
def housekeeping
at_exit { yield }
end
end
module RevisionMethods
module_function
def current_branch
@current_branch ||= `cat .git/HEAD | cut -d/ -f3,4,5`.chomp
end
def current_revision
`git rev-parse --short HEAD`.chomp
end
def revision_description(rev)
`git log --oneline -1 #{rev}`.chomp
end
def revisions(start_ref, end_ref)
cmd = "git rev-list --reverse #{start_ref}..#{end_ref}"
`#{cmd}`.chomp.split("\n")
end
def checkout_ref(ref)
`git checkout #{ref}`.chomp
if $CHILD_STATUS
STDERR.puts "Checkout failed: #{ref}, #{$CHILD_STATUS.exitstatus}" unless $CHILD_STATUS.success?
$CHILD_STATUS.success?
else
true
end
end
def clean_head
system('git reset --hard --quiet')
end
end
module ShellMethods
def sh(cmd)
puts cmd
# system(cmd)
run(cmd)
# env = {}
# # out = STDOUT
# pid = spawn(env, cmd)
# Process.wait(pid)
# pid = fork do
# exec cmd
# end
# Process.waitpid2(pid)
# puts $CHILD_STATUS.exitstatus
end
require 'pty'
# should consider trapping SIGINT in here
def run(cmd)
puts cmd
child_process = ''
result = ''
# http://stackoverflow.com/a/1162850
# stream output of subprocess
begin
PTY.spawn(cmd) do |stdin, _stdout, pid|
begin
# Do stuff with the output here. Just printing to show it works
stdin.each do |line|
print line
result << line
end
child_process = PTY.check(pid)
rescue Errno::EIO
puts 'Errno:EIO error, but this probably just means ' \
'that the process has finished giving output'
end
end
rescue PTY::ChildExited
puts 'The child process exited!'
end
unless (child_process && child_process.success?)
exitstatus = child_process.exitstatus
puts "FAILED: #{child_process.pid} exited with status #{exitstatus.inspect} due to failed command #{cmd}"
exit exitstatus || 1
end
result
end
def bundle(ref)
system("rm -f Gemfile.lock")
# This is absolutely critical for bundling to work
Bundler.with_clean_env do
system("bundle check ||
bundle install --local ||
bundle install ||
bundle update")
end
# if $CHILD_STATUS
# STDERR.puts "Bundle failed at: #{ref}, #{$CHILD_STATUS.exitstatus}" unless $CHILD_STATUS.success?
# $CHILD_STATUS.success?
# else
# false
# end
end
end
include ShellMethods
include RevisionMethods
def benchmark_refs(ref1: nil, ref2: nil, cmd:)
checking_out = false
ref0 = current_branch
ref1 ||= current_branch
ref2 ||= 'master'
p [ref0, ref1, ref2, current_revision]
run_benchmark_at_ref(cmd, ref1)
p [ref0, ref1, ref2, current_revision]
run_benchmark_at_ref(cmd, ref2)
p [ref0, ref1, ref2, current_revision]
checking_out = true
checkout_ref(ref0)
rescue Exception # rubocop:disable Lint/RescueException
STDERR.puts "[ERROR] #{$!.message}"
checkout_ref(ref0) unless checking_out
raise
end
def benchmark_revisions(ref1: nil, ref2: nil, cmd:)
checking_out = false
ref0 = current_branch
ref1 ||= current_branch
ref2 ||= 'master'
revisions(ref1, ref2).each do |rev|
STDERR.puts "Checking out: #{revision_description(rev)}"
run_benchmark_at_ref(cmd, rev)
clean_head
end
checking_out = true
checkout_ref(ref0)
rescue Exception # rubocop:disable Lint/RescueException
STDERR.puts "[ERROR]: #{$!.message}"
checkout_ref(ref0) unless checking_out
raise
end
def run_benchmark_at_ref(cmd, ref)
checkout_ref(ref)
run_benchmark(cmd, ref)
end
def run_benchmark(cmd, ref = nil)
ref ||= current_revision
bundle(ref) &&
benchmark_tests(cmd, ref)
end
def benchmark_tests(cmd, ref)
base = E_TMP_DIR
# cmd.sub('bin/bench', 'tmp/revision_runner/bench')
# bundle = Gem.bin('bunle'
# Bundler.with_clean_env(&block)
# cmd = Shellwords.shelljoin(cmd)
# cmd = "COMMIT_HASH=#{ref} BASE=#{base} bundle exec ruby -rbenchmark/ips #{cmd}"
# Add vendoring benchmark/ips to load path
# CURRENT THINKING: IMPORTANT
# Pass into require statement as RUBYOPTS i.e. via env rather than command line argument
# otherwise, have a 'fast ams benchmarking' module that extends benchmarkings to add the 'ams'
# method but doesn't depend on benchmark-ips
options = {
commit_hash: ref,
base: base,
rubyopt: Shellwords.shellescape("-Ilib:#{source_stasher.gem_require_paths.join(':')}")
}
BenchmarkDriver.parse_argv_and_run(ARGV.dup, options)
end
end
if $PROGRAM_NAME == __FILE__
benchmarking = BenchRegression.new
case ARGV[0]
when 'current'
# Run current branch only
# super simple command line parsing
args = ARGV.dup
_ = args.shift # remove 'current' from args
cmd = args
benchmarking.run_benchmark(cmd)
when 'revisions'
# Runs on every revision
# super simple command line parsing
args = ARGV.dup
_ = args.shift
ref1 = args.shift # remove 'revisions' from args
ref2 = args.shift
cmd = args
benchmarking.benchmark_revisions(ref1: ref1, ref2: ref2, cmd: cmd)
when 'vendor'
# Just prevents vendored files from being cleaned up
# at exit. (They are vendored at initialize.)
benchmarking.source_stasher.vendor = true
else
# Default: Compare current_branch to master
# Optionally: pass in two refs as args to `bin/bench_regression`
# TODO: Consider checking across more revisions, to automatically find problems.
# super simple command line parsing
args = ARGV.dup
ref1 = args.shift
ref2 = args.shift
cmd = args
benchmarking.benchmark_refs(ref1: ref1, ref2: ref2, cmd: cmd)
end
end
active_model_serializers-0.10.10/bin/rubocop 0000775 0000000 0000000 00000001434 13512322311 0021062 0 ustar 00root root 0000000 0000000 #!/usr/bin/env bash
#
# Usage:
# bin/rubocop [-A|-t|-h]
# bin/rubocop [file or path] [cli options]
#
# Options:
# Autocorrect -A
# AutoGenConfig -t
# Usage -h,--help,help
set -e
case $1 in
-A)
echo "Rubocop autocorrect is ON" >&2
bundle exec rake -f lib/tasks/rubocop.rake rubocop:auto_correct
;;
-t)
echo "Rubocop is generating a new TODO" >&2
bundle exec rake -f lib/tasks/rubocop.rake rubocop:auto_gen_config
;;
-h|--help|help)
sed -ne '/^#/!q;s/.\{1,2\}//;1d;p' < "$0"
;;
*)
# with no args, run vanilla rubocop
# else assume we're passing in arbitrary arguments
if [ -z "$1" ]; then
bundle exec rake -f lib/tasks/rubocop.rake rubocop
else
bundle exec rubocop "$@"
fi
;;
esac
active_model_serializers-0.10.10/bin/serve_benchmark 0000775 0000000 0000000 00000001330 13512322311 0022542 0 ustar 00root root 0000000 0000000 #!/usr/bin/env bash
set -e
case "$1" in
start)
config="${CONFIG_RU:-test/benchmark/config.ru}"
bundle exec ruby -Ilib -S rackup "$config" --daemonize --pid tmp/benchmark_app.pid --warn --server webrick
until [ -f 'tmp/benchmark_app.pid' ]; do
sleep 0.1 # give it time to start.. I don't know a better way
done
cat tmp/benchmark_app.pid
true
;;
stop)
if [ -f 'tmp/benchmark_app.pid' ]; then
kill -TERM $(cat tmp/benchmark_app.pid)
else
echo 'No pidfile'
false
fi
;;
status)
if [ -f 'tmp/benchmark_app.pid' ]; then
kill -0 $(cat tmp/benchmark_app.pid)
[ "$?" -eq 0 ]
else
echo 'No pidfile'
false
fi
;;
*)
echo "Usage: $0 [start|stop|status]"
;;
esac
active_model_serializers-0.10.10/docs/ 0000775 0000000 0000000 00000000000 13512322311 0017641 5 ustar 00root root 0000000 0000000 active_model_serializers-0.10.10/docs/README.md 0000664 0000000 0000000 00000003260 13512322311 0021121 0 ustar 00root root 0000000 0000000 # Docs - ActiveModel::Serializer 0.10.x
This is the documentation of ActiveModelSerializers, it's focused on the **0.10.x version.**
-----
## General
- [Getting Started](general/getting_started.md)
- [Configuration Options](general/configuration_options.md)
- [Serializers](general/serializers.md)
- [Adapters](general/adapters.md)
- [Rendering](general/rendering.md)
- [Caching](general/caching.md)
- [Logging](general/logging.md)
- [Deserialization](general/deserialization.md)
- [Instrumentation](general/instrumentation.md)
- JSON API
- [Schema](jsonapi/schema.md)
- [Errors](jsonapi/errors.md)
## How to
- [How to add root key](howto/add_root_key.md)
- [How to add pagination links](howto/add_pagination_links.md)
- [How to add relationship links](howto/add_relationship_links.md)
- [Using ActiveModelSerializers Outside Of Controllers](howto/outside_controller_use.md)
- [Testing ActiveModelSerializers](howto/test.md)
- [Passing Arbitrary Options](howto/passing_arbitrary_options.md)
- [How to serialize a Plain-Old Ruby Object (PORO)](howto/serialize_poro.md)
- [How to upgrade from `0.8` to `0.10` safely](howto/upgrade_from_0_8_to_0_10.md)
## Integrations
| Integration | Supported ActiveModelSerializers versions | Gem name and/or link
|----|-----|----
| Ember.js | 0.9.x | [active-model-adapter](https://github.com/ember-data/active-model-adapter)
| Ember.js | 0.10.x + | [docs/integrations/ember-and-json-api.md](integrations/ember-and-json-api.md)
| Grape | 0.10.x + | [docs/integrations/grape.md](integrations/grape.md) |
| Grape | 0.9.x | https://github.com/jrhe/grape-active_model_serializers/ |
| Sinatra | 0.9.x | https://github.com/SauloSilva/sinatra-active-model-serializers/
active_model_serializers-0.10.10/docs/STYLE.md 0000664 0000000 0000000 00000006223 13512322311 0021066 0 ustar 00root root 0000000 0000000 # STYLE
## Code and comments
- We are actively working to identify tasks under the label [**Good for New
Contributors**](https://github.com/rails-api/active_model_serializers/labels/Good%20for%20New%20Contributors).
- [Changelog
Missing](https://github.com/rails-api/active_model_serializers/issues?q=label%3A%22Changelog+Missing%22+is%3Aclosed) is
an easy way to help out.
- [Fix a bug](https://github.com/rails-api/active_model_serializers/labels/Ready%20for%20PR).
- Ready for PR - A well defined bug, needs someone to PR a fix.
- Bug - Anything that is broken.
- Regression - A bug that did not exist in previous versions and isn't a new feature (applied in tandem with Bug).
- Performance - A performance related issue. We could track this as a bug, but usually these would have slightly lower priority than standard bugs.
- [Develop new features](https://github.com/rails-api/active_model_serializers/labels/Feature).
- [Improve code quality](https://codeclimate.com/github/rails-api/active_model_serializers/code?sort=smell_count&sort_direction=desc).
- [Improve amount of code exercised by tests](https://codeclimate.com/github/rails-api/active_model_serializers/coverage?sort=covered_percent&sort_direction=asc).
- [Fix RuboCop (Style) TODOS](https://github.com/rails-api/active_model_serializers/blob/master/.rubocop_todo.yml).
- Delete and offsense, run `rake rubocop` (or possibly `rake rubocop:auto_correct`),
and [submit a PR](CONTRIBUTING.md#submitting-a-pull-request-pr).
- We are also encouraging comments to substantial changes (larger than bugfixes and simple features) under an
"RFC" (Request for Comments) process before we start active development.
Look for the [**RFC**](https://github.com/rails-api/active_model_serializers/labels/RFC) label.
## Pull requests
- If the tests pass and the pull request looks good, a maintainer will merge it.
- If the pull request needs to be changed,
- you can change it by updating the branch you generated the pull request from
- either by adding more commits, or
- by force pushing to it
- A maintainer can make any changes themselves and manually merge the code in.
## Commit messages
- [A Note About Git Commit Messages](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
- [http://stopwritingramblingcommitmessages.com/](http://stopwritingramblingcommitmessages.com/)
- [ThoughtBot style guide](https://github.com/thoughtbot/guides/tree/master/style#git)
#### About Pull Requests (PR's)
- [Using Pull Requests](https://help.github.com/articles/using-pull-requests)
- [Github pull requests made easy](http://www.element84.com/github-pull-requests-made-easy.html)
- [Exercism Git Workflow](http://help.exercism.io/git-workflow.html).
- [Level up your Git](http://rakeroutes.com/blog/deliberate-git/)
- [All Your Open Source Code Are Belong To Us](http://www.benjaminfleischer.com/2013/07/30/all-your-open-source-code-are-belong-to-us/)
## Issue Labeling
ActiveModelSerializers uses a subset of [StandardIssueLabels](https://github.com/wagenet/StandardIssueLabels) for Github Issues. You can [see our labels here](https://github.com/rails-api/active_model_serializers/labels).
active_model_serializers-0.10.10/docs/general/ 0000775 0000000 0000000 00000000000 13512322311 0021256 5 ustar 00root root 0000000 0000000 active_model_serializers-0.10.10/docs/general/adapters.md 0000664 0000000 0000000 00000017565 13512322311 0023421 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Adapters
ActiveModelSerializers offers the ability to configure which adapter
to use both globally and/or when serializing (usually when rendering).
The global adapter configuration is set on [`ActiveModelSerializers.config`](configuration_options.md).
It should be set only once, preferably at initialization.
For example:
```ruby
ActiveModelSerializers.config.adapter = ActiveModelSerializers::Adapter::JsonApi
```
or
```ruby
ActiveModelSerializers.config.adapter = :json_api
```
or
```ruby
ActiveModelSerializers.config.adapter = :json
```
The local adapter option is in the format `adapter: adapter`, where `adapter` is
any of the same values as set globally.
The configured adapter can be set as a symbol, class, or class name, as described in
[Advanced adapter configuration](adapters.md#advanced-adapter-configuration).
The `Attributes` adapter does not include a root key. It is just the serialized attributes.
Use either the `JSON` or `JSON API` adapters if you want the response document to have a root key.
***IMPORTANT***: Adapter configuration has *no effect* on a serializer instance
being used directly. That is, `UserSerializer.new(user).as_json` will *always*
behave as if the adapter were the 'Attributes' adapter. See [Outside Controller
Usage](../howto/outside_controller_use.md) for more details on recommended
usage.
## Built in Adapters
### Attributes - Default
It's the default adapter, it generates a json response without a root key.
Doesn't follow any specific convention.
##### Example output
```json
{
"title": "Title 1",
"body": "Body 1",
"publish_at": "2020-03-16T03:55:25.291Z",
"author": {
"first_name": "Bob",
"last_name": "Jones"
},
"comments": [
{
"body": "cool"
},
{
"body": "awesome"
}
]
}
```
### JSON
The json response is always rendered with a root key.
The root key can be overridden by:
* passing the `root` option in the render call. See details in the [Rendering Guides](rendering.md#overriding-the-root-key).
* setting the `type` of the serializer. See details in the [Serializers Guide](serializers.md#type).
Doesn't follow any specific convention.
##### Example output
```json
{
"post": {
"title": "Title 1",
"body": "Body 1",
"publish_at": "2020-03-16T03:55:25.291Z",
"author": {
"first_name": "Bob",
"last_name": "Jones"
},
"comments": [{
"body": "cool"
}, {
"body": "awesome"
}]
}
}
```
### JSON API
This adapter follows **version 1.0** of the [format specified](../jsonapi/schema.md) in
[jsonapi.org/format](http://jsonapi.org/format).
##### Example output
```json
{
"data": {
"id": "1337",
"type": "posts",
"attributes": {
"title": "Title 1",
"body": "Body 1",
"publish-at": "2020-03-16T03:55:25.291Z"
},
"relationships": {
"author": {
"data": {
"id": "1",
"type": "authors"
}
},
"comments": {
"data": [{
"id": "7",
"type": "comments"
}, {
"id": "12",
"type": "comments"
}]
}
},
"links": {
"post-authors": "https://example.com/post_authors"
},
"meta": {
"rating": 5,
"favorite-count": 10
}
}
}
```
### Include option
Which [serializer associations](https://github.com/rails-api/active_model_serializers/blob/master/docs/general/serializers.md#associations) are rendered can be specified using the `include` option. The option usage is consistent with [the include option in the JSON API spec](http://jsonapi.org/format/#fetching-includes), and is available in all adapters.
Example of the usage:
```ruby
render json: @posts, include: ['author', 'comments', 'comments.author']
# or
render json: @posts, include: 'author,comments,comments.author'
```
The format of the `include` option can be either:
- a String composed of a comma-separated list of [relationship paths](http://jsonapi.org/format/#fetching-includes).
- an Array of Symbols and Hashes.
- a mix of both.
An empty string or an empty array will prevent rendering of any associations.
In addition, two types of wildcards may be used:
- `*` includes one level of associations.
- `**` includes all recursively.
These can be combined with other paths.
```ruby
render json: @posts, include: '**' # or '*' for a single layer
```
The following would render posts and include:
- the author
- the author's comments, and
- every resource referenced by the author's comments (recursively).
It could be combined, like above, with other paths in any combination desired.
```ruby
render json: @posts, include: 'author.comments.**'
```
**Note:** Wildcards are ActiveModelSerializers-specific, they are not part of the JSON API spec.
The default include for the JSON API adapter is no associations. The default for the JSON and Attributes adapters is all associations.
For the JSON API adapter associated resources will be gathered in the `"included"` member. For the JSON and Attributes
adapters associated resources will be rendered among the other attributes.
Only for the JSON API adapter you can specify, which attributes of associated resources will be rendered. This feature
is called [sparse fieldset](http://jsonapi.org/format/#fetching-sparse-fieldsets):
```ruby
render json: @posts, include: 'comments', fields: { comments: ['content', 'created_at'] }
```
##### Security Considerations
Since the included options may come from the query params (i.e. user-controller):
```ruby
render json: @posts, include: params[:include]
```
The user could pass in `include=**`.
We recommend filtering any user-supplied includes appropriately.
## Advanced adapter configuration
### Registering an adapter
The default adapter can be configured, as above, to use any class given to it.
An adapter may also be specified, e.g. when rendering, as a class or as a symbol.
If a symbol, then the adapter must be, e.g. `:great_example`,
`ActiveModelSerializers::Adapter::GreatExample`, or registered.
There are two ways to register an adapter:
1) The simplest, is to subclass `ActiveModelSerializers::Adapter::Base`, e.g. the below will
register the `Example::UsefulAdapter` as `"example/useful_adapter"`.
```ruby
module Example
class UsefulAdapter < ActiveModelSerializers::Adapter::Base
end
end
```
You'll notice that the name it registers is the underscored namespace and class.
Under the covers, when the `ActiveModelSerializers::Adapter::Base` is subclassed, it registers
the subclass as `register("example/useful_adapter", Example::UsefulAdapter)`
2) Any class can be registered as an adapter by calling `register` directly on the
`ActiveModelSerializers::Adapter` class. e.g., the below registers `MyAdapter` as
`:special_adapter`.
```ruby
class MyAdapter; end
ActiveModelSerializers::Adapter.register(:special_adapter, MyAdapter)
```
### Looking up an adapter
| Method | Return value |
| :------------ |:---------------|
| `ActiveModelSerializers::Adapter.adapter_map` | A Hash of all known adapters `{ adapter_name => adapter_class }` |
| `ActiveModelSerializers::Adapter.adapters` | A (sorted) Array of all known `adapter_names` |
| `ActiveModelSerializers::Adapter.lookup(name_or_klass)` | The `adapter_class`, else raises an `ActiveModelSerializers::Adapter::UnknownAdapter` error |
| `ActiveModelSerializers::Adapter.adapter_class(adapter)` | Delegates to `ActiveModelSerializers::Adapter.lookup(adapter)` |
| `ActiveModelSerializers::Adapter.configured_adapter` | A convenience method for `ActiveModelSerializers::Adapter.lookup(config.adapter)` |
The registered adapter name is always a String, but may be looked up as a Symbol or String.
Helpfully, the Symbol or String is underscored, so that `get(:my_adapter)` and `get("MyAdapter")`
may both be used.
For more information, see [the Adapter class on GitHub](https://github.com/rails-api/active_model_serializers/blob/master/lib/active_model_serializers/adapter.rb)
active_model_serializers-0.10.10/docs/general/caching.md 0000664 0000000 0000000 00000004056 13512322311 0023201 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Caching
## Warning
There is currently a problem with caching in AMS [Caching doesn't improve performance](https://github.com/rails-api/active_model_serializers/issues/1586). Adding caching _may_ slow down your application, rather than speeding it up. We suggest you benchmark any caching you implement before using in a production enviroment
___
To cache a serializer, call ```cache``` and pass its options.
The options are the same options of ```ActiveSupport::Cache::Store```, plus
a ```key``` option that will be the prefix of the object cache
on a pattern ```"#{key}/#{object.id}-#{object.updated_at}"```.
The cache support is optimized to use the cached object in multiple request. An object cached on a ```show``` request will be reused at the ```index```. If there is a relationship with another cached serializer it will also be created and reused automatically.
**[NOTE] Every object is individually cached.**
**[NOTE] The cache is automatically expired after an object is updated, but it's not deleted.**
```ruby
cache(options = nil) # options: ```{key, expires_in, compress, force, race_condition_ttl}```
```
Take the example below:
```ruby
class PostSerializer < ActiveModel::Serializer
cache key: 'post', expires_in: 3.hours
attributes :title, :body
has_many :comments
end
```
On this example every ```Post``` object will be cached with
the key ```"post/#{post.id}-#{post.updated_at}"```. You can use this key to expire it as you want,
but in this case it will be automatically expired after 3 hours.
## Fragment Caching
If there is some API endpoint that shouldn't be fully cached, you can still optimise it, using Fragment Cache on the attributes and relationships that you want to cache.
You can define the attribute by using ```only``` or ```except``` option on cache method.
**[NOTE] Cache serializers will be used at their relationships**
Example:
```ruby
class PostSerializer < ActiveModel::Serializer
cache key: 'post', expires_in: 3.hours, only: [:title]
attributes :title, :body
has_many :comments
end
```
active_model_serializers-0.10.10/docs/general/configuration_options.md 0000664 0000000 0000000 00000012123 13512322311 0026221 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Configuration Options
The following configuration options can be set on
`ActiveModelSerializers.config`, preferably inside an initializer.
## General
##### adapter
The [adapter](adapters.md) to use.
Possible values:
- `:attributes` (default)
- `:json`
- `:json_api`
##### serializer_lookup_enabled
Enable automatic serializer lookup.
Possible values:
- `true` (default)
- `false`
When `false`, serializers must be explicitly specified.
##### key_transform
The [key transform](key_transforms.md) to use.
| Option | Result |
|----|----|
| `:camel` | ExampleKey |
| `:camel_lower` | exampleKey |
| `:dash` | example-key |
| `:unaltered` | the original, unaltered key |
| `:underscore` | example_key |
| `nil` | use the adapter default |
Each adapter has a default key transform configured:
| Adapter | Default Key Transform |
|----|----|
| `Attributes` | `:unaltered` |
| `Json` | `:unaltered` |
| `JsonApi` | `:dash` |
`config.key_transform` is a global override of the adapter default. Adapters
still prefer the render option `:key_transform` over this setting.
*NOTE: Key transforms can be expensive operations. If key transforms are unnecessary for the
application, setting `config.key_transform` to `:unaltered` will provide a performance boost.*
##### default_includes
What relationships to serialize by default. Default: `'*'`, which includes one level of related
objects. See [includes](adapters.md#included) for more info.
##### serializer_lookup_chain
Configures how serializers are searched for. By default, the lookup chain is
```ruby
ActiveModelSerializers::LookupChain::DEFAULT
```
which is shorthand for
```ruby
[
ActiveModelSerializers::LookupChain::BY_PARENT_SERIALIZER,
ActiveModelSerializers::LookupChain::BY_NAMESPACE,
ActiveModelSerializers::LookupChain::BY_RESOURCE_NAMESPACE,
ActiveModelSerializers::LookupChain::BY_RESOURCE
]
```
Each of the array entries represent a proc. A serializer lookup proc will be yielded 3 arguments. `resource_class`, `serializer_class`, and `namespace`.
Note that:
- `resource_class` is the class of the resource being rendered
- by default `serializer_class` is `ActiveModel::Serializer`
- for association lookup it's the "parent" serializer
- `namespace` correspond to either the controller namespace or the [optionally] specified [namespace render option](./rendering.md#namespace)
An example config could be:
```ruby
ActiveModelSerializers.config.serializer_lookup_chain = [
lambda do |resource_class, serializer_class, namespace|
"API::#{namespace}::#{resource_class}"
end
]
```
If you simply want to add to the existing lookup_chain. Use `unshift`.
```ruby
ActiveModelSerializers.config.serializer_lookup_chain.unshift(
lambda do |resource_class, serializer_class, namespace|
# ...
end
)
```
See [lookup_chain.rb](https://github.com/rails-api/active_model_serializers/blob/master/lib/active_model_serializers/lookup_chain.rb) for further explanations and examples.
## JSON API
##### jsonapi_resource_type
Sets whether the [type](http://jsonapi.org/format/#document-resource-identifier-objects)
of the resource should be `singularized` or `pluralized` when it is not
[explicitly specified by the serializer](https://github.com/rails-api/active_model_serializers/blob/master/docs/general/serializers.md#type)
Possible values:
- `:singular`
- `:plural` (default)
##### jsonapi_namespace_separator
Sets separator string for namespaced models to render `type` attribute.
| Separator | Example: Admin::User |
|----|----|
| `'-'` (default) | 'admin-users'
| `'--'` (recommended) | 'admin--users'
See [Recommendation for dasherizing (kebab-case-ing) namespaced object, such as `Admin::User`](https://github.com/json-api/json-api/issues/850)
for more discussion.
##### jsonapi_include_toplevel_object
Include a [top level jsonapi member](http://jsonapi.org/format/#document-jsonapi-object)
in the response document.
Possible values:
- `true`
- `false` (default)
##### jsonapi_version
The latest version of the spec to which the API conforms.
Default: `'1.0'`.
*Used when `jsonapi_include_toplevel_object` is `true`*
##### jsonapi_toplevel_meta
Optional top-level metadata. Not included if empty.
Default: `{}`.
*Used when `jsonapi_include_toplevel_object` is `true`*
##### jsonapi_use_foreign_key_on_belongs_to_relationship
When true, the relationship will determine its resource object identifier
without calling the association or its serializer. This can be useful when calling
the association object is triggering unnecessary queries.
For example, if a `comment` belongs to a `post`, and the comment
uses the foreign key `post_id`, we can determine the resource object
identifier `id` as `comment.post_id` and the `type` from the association options.
Or quite simply, it behaves as `belongs_to :post, type: :posts, foreign_key: :post_id`.
Note: This option has *no effect* on polymorphic associations as we cannot reliably
determine the associated object's type without instantiating it.
Default: `false`.
## Hooks
To run a hook when ActiveModelSerializers is loaded, use
`ActiveSupport.on_load(:action_controller) do end`
active_model_serializers-0.10.10/docs/general/deserialization.md 0000664 0000000 0000000 00000004616 13512322311 0024775 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Deserialization
This is currently an *experimental* feature. The interface may change.
## JSON API
The `ActiveModelSerializers::Deserialization` defines two methods (namely `jsonapi_parse` and `jsonapi_parse!`), which take a `Hash` or an instance of `ActionController::Parameters` representing a JSON API payload, and return a hash that can directly be used to create/update models. The bang version throws an `InvalidDocument` exception when parsing fails, whereas the "safe" version simply returns an empty hash.
- Parameters
- document: `Hash` or `ActionController::Parameters` instance
- options:
- only: `Array` of whitelisted fields
- except: `Array` of blacklisted fields
- keys: `Hash` of fields the name of which needs to be modified (e.g. `{ :author => :user, :date => :created_at }`)
Examples:
```ruby
class PostsController < ActionController::Base
def create
Post.create(create_params)
end
def create_params
ActiveModelSerializers::Deserialization.jsonapi_parse(params, only: [:title, :content, :author])
end
end
```
Given a JSON API document,
```
document = {
'data' => {
'id' => 1,
'type' => 'post',
'attributes' => {
'title' => 'Title 1',
'date' => '2015-12-20'
},
'relationships' => {
'author' => {
'data' => {
'type' => 'user',
'id' => '2'
}
},
'second_author' => {
'data' => nil
},
'comments' => {
'data' => [{
'type' => 'comment',
'id' => '3'
},{
'type' => 'comment',
'id' => '4'
}]
}
}
}
}
```
The entire document can be parsed without specifying any options:
```ruby
ActiveModelSerializers::Deserialization.jsonapi_parse(document)
#=>
# {
# title: 'Title 1',
# date: '2015-12-20',
# author_id: 2,
# second_author_id: nil
# comment_ids: [3, 4]
# }
```
and fields, relationships, and polymorphic relationships can be specified via the options:
```ruby
ActiveModelSerializers::Deserialization
.jsonapi_parse(document, only: [:title, :date, :author],
keys: { date: :published_at },
polymorphic: [:author])
#=>
# {
# title: 'Title 1',
# published_at: '2015-12-20',
# author_id: '2',
# author_type: 'user'
# }
```
## Attributes/Json
There is currently no deserialization for those adapters.
active_model_serializers-0.10.10/docs/general/fields.md 0000664 0000000 0000000 00000001434 13512322311 0023050 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Fields
If for any reason, you need to restrict the fields returned, you should use `fields` option.
For example, if you have a serializer like this
```ruby
class UserSerializer < ActiveModel::Serializer
attributes :access_token, :first_name, :last_name
end
```
and in a specific controller, you want to return `access_token` only, `fields` will help you:
```ruby
class AnonymousController < ApplicationController
def create
render json: User.create(activation_state: 'anonymous'), fields: [:access_token], status: 201
end
end
```
Note that this is only valid for the `json` and `attributes` adapter. For the `json_api` adapter, you would use
```ruby
render json: @user, fields: { users: [:access_token] }
```
Where `users` is the JSONAPI type.
active_model_serializers-0.10.10/docs/general/getting_started.md 0000664 0000000 0000000 00000007057 13512322311 0025000 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Getting Started
## Creating a Serializer
The easiest way to create a new serializer is to generate a new resource, which
will generate a serializer at the same time:
```
$ rails g resource post title:string body:string
```
This will generate a serializer in `app/serializers/post_serializer.rb` for
your new model. You can also generate a serializer for an existing model with
the serializer generator:
```
$ rails g serializer post
```
The generated serializer will contain basic `attributes` and
`has_many`/`has_one`/`belongs_to` declarations, based on the model. For example:
```ruby
class PostSerializer < ActiveModel::Serializer
attributes :title, :body
has_many :comments
has_one :author
end
```
and
```ruby
class CommentSerializer < ActiveModel::Serializer
attributes :name, :body
belongs_to :post
end
```
The attribute names are a **whitelist** of attributes to be serialized.
The `has_many`, `has_one`, and `belongs_to` declarations describe relationships between
resources. By default, when you serialize a `Post`, you will get its `Comments`
as well.
For more information, see [Serializers](/docs/general/serializers.md).
### Namespaced Models
When serializing a model inside a namespace, such as `Api::V1::Post`, ActiveModelSerializers will expect the corresponding serializer to be inside the same namespace (namely `Api::V1::PostSerializer`).
### Model Associations and Nested Serializers
When declaring a serializer for a model with associations, such as:
```ruby
class PostSerializer < ActiveModel::Serializer
has_many :comments
end
```
ActiveModelSerializers will look for `PostSerializer::CommentSerializer` in priority, and fall back to `::CommentSerializer` in case the former does not exist. This allows for more control over the way a model gets serialized as an association of an other model.
For example, in the following situation:
```ruby
class CommentSerializer < ActiveModel::Serializer
attributes :body, :date, :nb_likes
end
class PostSerializer < ActiveModel::Serializer
has_many :comments
class CommentSerializer < ActiveModel::Serializer
attributes :body_short
end
end
```
ActiveModelSerializers will use `PostSerializer::CommentSerializer` (thus including only the `:body_short` attribute) when serializing a `Comment` as part of a `Post`, but use `::CommentSerializer` when serializing a `Comment` directly (thus including `:body, :date, :nb_likes`).
### Extending a Base `ApplicationSerializer`
By default, new serializers descend from `ActiveModel::Serializer`. However, if
you wish to share behavior across your serializers, you can create an
`ApplicationSerializer` at `app/serializers/application_serializer.rb`:
```ruby
class ApplicationSerializer < ActiveModel::Serializer
end
```
Then any newly-generated serializers will automatically descend from
`ApplicationSerializer`.
```
$ rails g serializer post
```
Now generates:
```ruby
class PostSerializer < ApplicationSerializer
attributes :id
end
````
## Rails Integration
ActiveModelSerializers will automatically integrate with your Rails app,
so you won't need to update your controller.
This is a example of how the controller will look:
```ruby
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
render json: @post
end
end
```
If you wish to use Rails url helpers for link generation, e.g., `link(:resources) { resources_url }`, ensure your application sets
`Rails.application.routes.default_url_options`.
```ruby
Rails.application.routes.default_url_options = {
host: 'example.com'
}
```
active_model_serializers-0.10.10/docs/general/instrumentation.md 0000664 0000000 0000000 00000001751 13512322311 0025047 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Instrumentation
ActiveModelSerializers uses the
[ActiveSupport::Notification API](http://guides.rubyonrails.org/active_support_instrumentation.html#subscribing-to-an-event),
which allows for subscribing to events, such as for logging.
## Events
Name:
`render.active_model_serializers`
Payload (example):
```ruby
{
serializer: PostSerializer,
adapter: ActiveModelSerializers::Adapter::Attributes
}
```
Subscribing:
```ruby
ActiveSupport::Notifications.subscribe 'render.active_model_serializers' do |name, started, finished, unique_id, data|
# whatever
end
ActiveSupport::Notifications.subscribe 'render.active_model_serializers' do |*args|
event = ActiveSupport::Notifications::Event.new(*args)
# event.payload
# whatever
end
```
## [LogSubscriber](http://api.rubyonrails.org/classes/ActiveSupport/LogSubscriber.html)
ActiveModelSerializers includes an `ActiveModelSerializers::LogSubscriber` that attaches to
`render.active_model_serializers`.
active_model_serializers-0.10.10/docs/general/key_transforms.md 0000664 0000000 0000000 00000001667 13512322311 0024660 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Key Transforms
Key Transforms modify the casing of keys and keys referenced in values in
serialized responses.
Provided key transforms:
| Option | Result |
|----|----|
| `:camel` | ExampleKey |
| `:camel_lower` | exampleKey |
| `:dash` | example-key |
| `:unaltered` | the original, unaltered key |
| `:underscore` | example_key |
| `nil` | use the adapter default |
Key translation precedence is as follows:
##### Adapter option
`key_transform` is provided as an option via render.
```render json: posts, each_serializer: PostSerializer, key_transform: :camel_lower```
##### Configuration option
`key_transform` is set in `ActiveModelSerializers.config.key_transform`.
```ActiveModelSerializers.config.key_transform = :camel_lower```
##### Adapter default
Each adapter has a default transform configured:
| Adapter | Default Key Transform |
|----|----|
| `Json` | `:unaltered` |
| `JsonApi` | `:dash` |
active_model_serializers-0.10.10/docs/general/logging.md 0000664 0000000 0000000 00000001122 13512322311 0023222 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Logging
The default logger in a Rails application will be `Rails.logger`.
When there is no `Rails.logger`, the default logger is an instance of
`ActiveSupport::TaggedLogging` logging to STDOUT.
You may customize the logger in an initializer, for example:
```ruby
ActiveModelSerializers.logger = Logger.new(STDOUT)
```
You can also disable the logger, just put this in `config/initializers/active_model_serializers.rb`:
```ruby
require 'active_model_serializers'
ActiveSupport::Notifications.unsubscribe(ActiveModelSerializers::Logging::RENDER_EVENT)
```
active_model_serializers-0.10.10/docs/general/rendering.md 0000664 0000000 0000000 00000016006 13512322311 0023560 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Rendering
### Implicit Serializer
In your controllers, when you use `render :json`, Rails will now first search
for a serializer for the object and use it if available.
```ruby
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
render json: @post
end
end
```
In this case, Rails will look for a serializer named `PostSerializer`, and if
it exists, use it to serialize the `Post`.
### Explicit Serializer
If you wish to use a serializer other than the default, you can explicitly pass it to the renderer.
#### 1. For a resource:
```ruby
render json: @post, serializer: PostPreviewSerializer
```
#### 2. For a resource collection:
Specify the serializer for each resource with `each_serializer`
```ruby
render json: @posts, each_serializer: PostPreviewSerializer
```
The default serializer for collections is `CollectionSerializer`.
Specify the collection serializer with the `serializer` option.
```ruby
render json: @posts, serializer: CollectionSerializer, each_serializer: PostPreviewSerializer
```
## Serializing non-ActiveRecord objects
See [README](../../README.md#what-does-a-serializable-resource-look-like)
## SerializableResource options
See [README](../../README.md#activemodelserializersserializableresource)
### adapter_opts
#### fields
If you are using `json` or `attributes` adapter
```ruby
render json: @user, fields: [:access_token]
```
See [Fields](fields.md) for more information.
#### adapter
This option lets you explicitly set the adapter to be used by passing a registered adapter. Your options are `:attributes`, `:json`, and `:json_api`.
```
ActiveModel::Serializer.config.adapter = :json_api
```
#### key_transform
```render json: posts, each_serializer: PostSerializer, key_transform: :camel_lower```
See [Key Transforms](key_transforms.md) for more information.
#### meta
A `meta` member can be used to include non-standard meta-information. `meta` can
be utilized in several levels in a response.
##### Top-level
To set top-level `meta` in a response, specify it in the `render` call.
```ruby
render json: @post, meta: { total: 10 }
```
The key can be customized using `meta_key` option.
```ruby
render json: @post, meta: { total: 10 }, meta_key: "custom_meta"
```
`meta` will only be included in your response if you are using an Adapter that
supports `root`, e.g., `JsonApi` and `Json` adapters. The default adapter,
`Attributes` does not have `root`.
##### Resource-level
To set resource-level `meta` in a response, define meta in a serializer with one
of the following methods:
As a single, static string.
```ruby
meta stuff: 'value'
```
As a block containing a Hash.
```ruby
meta do
{
rating: 4,
comments_count: object.comments.count
}
end
```
#### links
If you wish to use Rails url helpers for link generation, e.g., `link(:resources) { resources_url }`, ensure your application sets
`Rails.application.routes.default_url_options`.
##### Top-level
JsonApi supports a [links object](http://jsonapi.org/format/#document-links) to be specified at top-level, that you can specify in the `render`:
```ruby
links_object = {
href: "http://example.com/api/posts",
meta: {
count: 10
}
}
render json: @posts, links: links_object
```
That's the result:
```json
{
"data": [
{
"type": "posts",
"id": "1",
"attributes": {
"title": "JSON API is awesome!",
"body": "You should be using JSON API",
"created": "2015-05-22T14:56:29.000Z",
"updated": "2015-05-22T14:56:28.000Z"
}
}
],
"links": {
"href": "http://example.com/api/posts",
"meta": {
"count": 10
}
}
}
```
This feature is specific to JsonApi, so you have to use the use the [JsonApi Adapter](adapters.md#jsonapi)
##### Resource-level
In your serializer, define each link in one of the following methods:
As a static string
```ruby
link :link_name, 'https://example.com/resource'
```
As a block to be evaluated. When using Rails, URL helpers are available.
Ensure your application sets `Rails.application.routes.default_url_options`.
```ruby
link :link_name_ do
"https://example.com/resource/#{object.id}"
end
link(:link_name) { "https://example.com/resource/#{object.id}" }
link(:link_name) { resource_url(object) }
link(:link_name) { url_for(controller: 'controller_name', action: 'index', only_path: false) }
```
### serializer_opts
#### include
See [Adapters: Include Option](/docs/general/adapters.md#include-option).
#### Overriding the root key
Overriding the resource root only applies when using the JSON adapter.
Normally, the resource root is derived from the class name of the resource being serialized.
e.g. `UserPostSerializer.new(UserPost.new)` will be serialized with the root `user_post` or `user_posts` according the adapter collection pluralization rules.
When using the JSON adapter in your initializer (ActiveModelSerializers.config.adapter = :json), or passing in the adapter in your render call, you can specify the root by passing it as an argument to `render`. For example:
```ruby
render json: @user_post, root: "admin_post", adapter: :json
```
This will be rendered as:
```json
{
"admin_post": {
"title": "how to do open source"
}
}
```
Note: the `Attributes` adapter (default) does not include a resource root. You also will not be able to create a single top-level root if you are using the :json_api adapter.
#### namespace
The namespace for serializer lookup is based on the controller.
To configure the implicit namespace, in your controller, create a before filter
```ruby
before_action do
self.namespace_for_serializer = Api::V2
end
```
`namespace` can also be passed in as a render option:
```ruby
@post = Post.first
render json: @post, namespace: Api::V2
```
This tells the serializer lookup to check for the existence of `Api::V2::PostSerializer`, and if any relations are rendered with `@post`, they will also utilize the `Api::V2` namespace.
The `namespace` can be any object whose namespace can be represented by string interpolation (i.e. by calling to_s)
- Module `Api::V2`
- String `'Api::V2'`
- Symbol `:'Api::V2'`
Note that by using a string and symbol, Ruby will assume the namespace is defined at the top level.
#### serializer
Specify which serializer to use if you want to use a serializer other than the default.
For a single resource:
```ruby
@post = Post.first
render json: @post, serializer: SpecialPostSerializer
```
To specify which serializer to use on individual items in a collection (i.e., an `index` action), use `each_serializer`:
```ruby
@posts = Post.all
render json: @posts, each_serializer: SpecialPostSerializer
```
#### scope
See [Serializers: Scope](/docs/general/serializers.md#scope).
#### scope_name
See [Serializers: Scope](/docs/general/serializers.md#scope).
## Using a serializer without `render`
See [Usage outside of a controller](../howto/outside_controller_use.md#serializing-before-controller-render).
## Pagination
See [How to add pagination links](../howto/add_pagination_links.md).
active_model_serializers-0.10.10/docs/general/serializers.md 0000664 0000000 0000000 00000033530 13512322311 0024140 0 ustar 00root root 0000000 0000000 [Back to Guides](../README.md)
# Serializers
Given a serializer class:
```ruby
class SomeSerializer < ActiveModel::Serializer
end
```
The following methods may be defined in it:
### Attributes
#### ::attributes
Serialization of the resource `title` and `body`
| In Serializer | #attributes |
|---------------------------- |-------------|
| `attributes :title, :body` | `{ title: 'Some Title', body: 'Some Body' }`
| `attributes :title, :body`
`def body "Special #{object.body}" end` | `{ title: 'Some Title', body: 'Special Some Body' }`
#### ::attribute
Serialization of the resource `title`
| In Serializer | #attributes |
|---------------------------- |-------------|
| `attribute :title` | `{ title: 'Some Title' } `
| `attribute :title, key: :name` | `{ name: 'Some Title' } `
| `attribute(:title) { 'A Different Title'}` | `{ title: 'A Different Title' } `
| `attribute :title`
`def title 'A Different Title' end` | `{ title: 'A Different Title' }`
An `if` or `unless` option can make an attribute conditional. It takes a symbol of a method name on the serializer, or a lambda literal.
e.g.
```ruby
attribute :private_data, if: :is_current_user?
attribute :another_private_data, if: -> { scope.admin? }
def is_current_user?
object.id == current_user.id
end
```
### Associations
The interface for associations is, generically:
> `association_type(association_name, options, &block)`
Where:
- `association_type` may be `has_one`, `has_many`, `belongs_to`.
- `association_name` is a method name the serializer calls.
- optional: `options` may be:
- `key:` The name used for the serialized association.
- `serializer:`
- `if:`
- `unless:`
- `virtual_value:`
- `polymorphic:` defines if polymorphic relation type should be nested in serialized association.
- `type:` the resource type as used by JSON:API, especially on a `belongs_to` relationship.
- `class_name:` the (String) model name used to determine `type`, when `type` is not given. e.g. `class_name: "Comment"` would imply the type `comments`
- `foreign_key:` used by JSON:API on a `belongs_to` relationship to avoid unnecessarily loading the association object.
- `namespace:` used when looking up the serializer and `serializer` is not given. Falls back to the parent serializer's `:namespace` instance options, which, when present, comes from the render options. See [Rendering#namespace](rendering.md#namespace] for more details.
- optional: `&block` is a context that returns the association's attributes.
- prevents `association_name` method from being called.
- return value of block is used as the association value.
- yields the `serializer` to the block.
- `include_data false` prevents the `data` key from being rendered in the JSON API relationship.
#### ::has_one
e.g.
```ruby
has_one :bio
has_one :blog, key: :site
has_one :blog, class_name: "Blog"
has_one :maker, virtual_value: { id: 1 }
has_one :blog do |serializer|
serializer.cached_blog
end
def cached_blog
cache_store.fetch("cached_blog:#{object.updated_at}") do
Blog.find(object.blog_id)
end
end
```
```ruby
has_one :blog, if: :show_blog?
# you can also use a string or lambda
# has_one :blog, if: 'scope.admin?'
# has_one :blog, if: -> (serializer) { serializer.scope.admin? }
# has_one :blog, if: -> { scope.admin? }
def show_blog?
scope.admin?
end
```
#### ::has_many
e.g.
```ruby
has_many :comments
has_many :comments, key: :reviews
has_many :comments, serializer: CommentPreviewSerializer
has_many :comments, class_name: "Comment"
has_many :reviews, virtual_value: [{ id: 1 }, { id: 2 }]
has_many :comments, key: :last_comments do
last(1)
end
```
#### ::belongs_to
e.g.
```ruby
belongs_to :author, serializer: AuthorPreviewSerializer
belongs_to :author, key: :writer
belongs_to :author, class_name: "Author"
belongs_to :post
belongs_to :blog
def blog
Blog.new(id: 999, name: 'Custom blog')
end
```
### Polymorphic Relationships
Polymorphic relationships are serialized by specifying the relationship, like any other association. For example:
```ruby
class PictureSerializer < ActiveModel::Serializer
has_one :imageable
end
```
You can specify the serializers by [overriding serializer_for](serializers.md#overriding-association-serializer-lookup). For more context about polymorphic relationships, see the [tests](../../test/adapter/polymorphic_test.rb) for each adapter.
### Caching
#### ::cache
e.g.
```ruby
cache key: 'post', expires_in: 0.1, skip_digest: true
cache expires_in: 1.day, skip_digest: true
cache key: 'writer', skip_digest: true
cache only: [:name], skip_digest: true
cache except: [:content], skip_digest: true
cache key: 'blog'
cache only: [:id]
```
#### #cache_key
e.g.
```ruby
# Uses a custom non-time-based cache key
def cache_key
"#{self.class.name.downcase}/#{self.id}"
end
```
### Other
#### ::type
When using the `:json_api` adapter, the `::type` method defines the JSONAPI [type](http://jsonapi.org/format/#document-resource-object-identification) that will be rendered for this serializer.
When using the `:json` adapter, the `::type` method defines the name of the root element.
It either takes a `String` or `Symbol` as parameter.
Note: This method is useful only when using the `:json_api` or `:json` adapter.
Examples:
```ruby
class UserProfileSerializer < ActiveModel::Serializer
type 'profile'
attribute :name
end
class AuthorProfileSerializer < ActiveModel::Serializer
type :profile
attribute :name
end
```
With the `:json_api` adapter, the previous serializers would be rendered as:
``` json
{
"data": {
"id": "1",
"type": "profile",
"attributes": {
"name": "Julia"
}
}
}
```
With the `:json` adapter, the previous serializer would be rendered as:
``` json
{
"profile": {
"name": "Julia"
}
}
```
#### ::link
```ruby
link :self do
href "https://example.com/link_author/#{object.id}"
end
link(:author) { link_author_url(object) }
link(:link_authors) { link_authors_url }
link :other, 'https://example.com/resource'
link(:posts) { link_author_posts_url(object) }
```
Just like attributes, links also support conditions in options
```ruby
link(:secret, if: :internal?) { object.secret_link }
def internal?
instance_options[:context] == :internal
end
```
#### #object
The object being serialized.
#### #root
Resource root which is included in `JSON` adapter. As you can see at [Adapters Document](adapters.md), `Attribute` adapter (default) and `JSON API` adapter does not include root at top level.
By default, the resource root comes from the `model_name` of the serialized object's class.
There are several ways to specify root:
* [Overriding the root key](rendering.md#overriding-the-root-key)
* [Setting `type`](serializers.md#type)
* Specifying the `root` option, e.g. `root: 'specific_name'`, during the serializer's initialization:
```ruby
ActiveModelSerializers::SerializableResource.new(foo, root: 'bar')
```
#### #scope
Allows you to include in the serializer access to an external method.
It's intended to provide an authorization context to the serializer, so that
you may e.g. show an admin all comments on a post, else only published comments.
- `scope` is a method on the serializer instance that comes from `options[:scope]`. It may be nil.
- `scope_name` is an option passed to the new serializer (`options[:scope_name]`). The serializer
defines a method with that name that calls the `scope`, e.g. `def current_user; scope; end`.
Note: it does not define the method if the serializer instance responds to it.
That's a lot of words, so here's some examples:
First, let's assume the serializer is instantiated in the controller, since that's the usual scenario.
We'll refer to the serialization context as `controller`.
| options | `Serializer#scope` | method definition |
|-------- | ------------------|--------------------|
| `scope: current_user, scope_name: :current_user` | `current_user` | `Serializer#current_user` calls `controller.current_user`
| `scope: view_context, scope_name: :view_context` | `view_context` | `Serializer#view_context` calls `controller.view_context`
We can take advantage of the scope to customize the objects returned based
on the current user (scope).
For example, we can limit the posts the current user sees to those they created:
```ruby
class PostSerializer < ActiveModel::Serializer
attributes :id, :title, :body
# scope comments to those created_by the current user
has_many :comments do
object.comments.where(created_by: current_user)
end
end
```
Whether you write the method as above or as `object.comments.where(created_by: scope)`
is a matter of preference (assuming `scope_name` has been set).
Keep in mind that the scope can be set to any available controller reference. This can be utilized to provide access to any other data scopes or presentation helpers.
##### Controller Authorization Context
In the controller, the scope/scope_name options are equal to
the [`serialization_scope`method](https://github.com/rails-api/active_model_serializers/blob/d02cd30fe55a3ea85e1d351b6e039620903c1871/lib/action_controller/serialization.rb#L13-L20),
which is `:current_user`, by default.
Specifically, the `scope_name` is defaulted to `:current_user`, and may be set as
`serialization_scope :view_context`. The `scope` is set to `send(scope_name)` when `scope_name` is
present and the controller responds to `scope_name`.
Thus, in a serializer, the controller provides `current_user` as the
current authorization scope when you call `render :json`.
**IMPORTANT**: Since the scope is set at render, you may want to customize it so that `current_user` isn't
called on every request. This was [also a problem](https://github.com/rails-api/active_model_serializers/pull/1252#issuecomment-159810477)
in [`0.9`](https://github.com/rails-api/active_model_serializers/tree/0-9-stable#customizing-scope).
We can change the scope from `current_user` to `view_context`, which is included in subclasses of `ActionController::Base`.
```diff
class SomeController < ActionController::Base
+ serialization_scope :view_context
def current_user
User.new(id: 2, name: 'Bob', admin: true)
end
def edit
user = User.new(id: 1, name: 'Pete')
render json: user, serializer: AdminUserSerializer, adapter: :json_api
end
end
```
We could then use the controller method `view_context` in our serializer, like so:
```diff
class AdminUserSerializer < ActiveModel::Serializer
attributes :id, :name, :can_edit
def can_edit?
+ view_context.current_user.admin?
end
end
```
So that when we render the `#edit` action, we'll get
```json
{"data":{"id":"1","type":"users","attributes":{"name":"Pete","can_edit":true}}}
```
Where `can_edit` is `view_context.current_user.admin?` (true).
You can also tell what to set as `serialization_scope` for specific actions.
For example, use `admin_user` only for `Admin::PostSerializer` and `current_user` for rest.
```ruby
class PostsController < ActionController::Base
before_action only: :edit do
self.class.serialization_scope :admin_user
end
def show
render json: @post, serializer: PostSerializer
end
def edit
@post.save
render json: @post, serializer: Admin::PostSerializer
end
private
def admin_user
User.new(id: 2, name: 'Bob', admin: true)
end
def current_user
User.new(id: 2, name: 'Bob', admin: false)
end
end
```
Note that any controller reference which provides the desired scope is acceptable, such as another controller method for loading a different resource or reference to helpers. For example, `ActionController::API` does not include `ActionView::ViewContext`, and would need a different reference for passing any helpers into a serializer via `serialization_scope`.
#### #read_attribute_for_serialization(key)
The serialized value for a given key. e.g. `read_attribute_for_serialization(:title) #=> 'Hello World'`
#### #links
Allows you to modify the `links` node. By default, this node will be populated with the attributes set using the [::link](#link) method. Using `links: nil` will remove the `links` node.
```ruby
ActiveModelSerializers::SerializableResource.new(
@post,
adapter: :json_api,
links: {
self: {
href: 'http://example.com/posts',
meta: {
stuff: 'value'
}
}
}
)
```
#### #json_key
Returns the key used by the adapter as the resource root. See [root](#root) for more information.
## Examples
Given two models, a `Post(title: string, body: text)` and a
`Comment(name: string, body: text, post_id: integer)`, you will have two
serializers:
```ruby
class PostSerializer < ActiveModel::Serializer
cache key: 'posts', expires_in: 3.hours
attributes :title, :body
has_many :comments
end
```
and
```ruby
class CommentSerializer < ActiveModel::Serializer
attributes :name, :body
belongs_to :post
end
```
Generally speaking, you, as a user of ActiveModelSerializers, will write (or generate) these
serializer classes.
## More Info
For more information, see [the Serializer class on GitHub](https://github.com/rails-api/active_model_serializers/blob/0-10-stable/lib/active_model/serializer.rb)
## Overriding association methods
To override an association, call `has_many`, `has_one` or `belongs_to` with a block:
```ruby
class PostSerializer < ActiveModel::Serializer
has_many :comments do
object.comments.active
end
end
```
## Overriding attribute methods
To override an attribute, call `attribute` with a block:
```ruby
class PostSerializer < ActiveModel::Serializer
attribute :body do
object.body.downcase
end
end
```
## Overriding association serializer lookup
If you want to define a specific serializer lookup for your associations, you can override
the `ActiveModel::Serializer.serializer_for` method to return a serializer class based on defined conditions.
```ruby
class MySerializer < ActiveModel::Serializer
def self.serializer_for(model, options)
return SparseAdminSerializer if model.class.name == 'Admin'
super
end
# the rest of the serializer
end
```
active_model_serializers-0.10.10/docs/how-open-source-maintained.jpg 0000664 0000000 0000000 00001050220 13512322311 0025504 0 ustar 00root root 0000000 0000000 ’Ų’į Exif II* ’ģ Ducky d ’įqhttp://ns.adobe.com/xap/1.0/ ’ī Adobe dĄ ’Ū ’Ą „ ’Ä
% ! 1A"Q
aq2#BRr3$”±bÖWXĮ¢²Cs³%ÕGYS4Ō&'ct5µÅ6v¶w×8ŃĀÓdeĘg·šŅ£ĆDT¤“EFVf7(ØI
!1AQaq”±ĮŃ"2RBr3šįb¢²#S4Ās5ŅCc$ń% ⣳TdtĆ6D’Ś ? ļń¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"h¢&"§vŚ„·5r¼Ł«ŌŹ
n=yk®×5]ĄE5/{©9©É,āā£ŪŖ.Ŗi:¹oH4jż¦ļ¾nĘOY®9H«6tÕŹ&:.øDå9C NQB¾C8óä×ęä×·”{³ćĶ/lkĖ=Q(§oŚČÄGĢĻ Ł7Q7p';gIÅ hNm4DŃDM4DŃDM4EŃē_äh\°ČÕ¬ĆYø×ø>ć(Ēr|µ
V#§pÜŻ!×'.0śŌ
ėĄ1s$eP9MŹm«®,ņWsXUō/ĢÕ&
óqį6%×pÉŌtŌa\;# 6KµtT]Nrģa"“<ķņÅŅyku”ŠÆŁ:@MDÓm lģ<ż
oX^61¤]ūµ×T 6āTŹ¢R ×AdÜ »Å' &²~¢J¢§¦© äļEb&²Gķ0nS¦(ōé¢-]c«ĘG;ł[ćÜ"8äĘż[æJcK&ĀFA[ėH
ŻĆ(ĀNXį$£Ā[.ŻćG«"ÆyÓÅRU2dWDVW\Į*Q#ÅäŅüUV 9§McČ»vś