```
require "rails/generators/rails/model/model_generator"
module Rails
module Generators
class ResourceGenerator < ModelGenerator # :nodoc:
include ResourceHelpers
hook_for :resource_controller, required: true do |controller|
invoke controller, [ controller_name, options[:actions] ]
end
class_option :actions, type: :array, banner: "ACTION ACTION", default: [],
desc: "Actions for the resource controller"
hook_for :resource_route, required: true
end
end
end
```
```
# .bundle/ruby/2.2.0/bundler/gems/rails-4c5f1bc9d45e/railties/lib/rails/generators/base.rb
# Invoke a generator based on the value supplied by the user to the
# given option named "name". A class option is created when this method
# is invoked and you can set a hash to customize it.
#
# ==== Examples
#
# module Rails::Generators
# class ControllerGenerator < Base
# hook_for :test_framework, aliases: "-t"
# end
# end
#
# The example above will create a test framework option and will invoke
# a generator based on the user supplied value.
#
# For example, if the user invoke the controller generator as:
#
# rails generate controller Account --test-framework=test_unit
#
# The controller generator will then try to invoke the following generators:
#
# "rails:test_unit", "test_unit:controller", "test_unit"
#
# Notice that "rails:generators:test_unit" could be loaded as well, what
# Rails looks for is the first and last parts of the namespace. This is what
# allows any test framework to hook into Rails as long as it provides any
# of the hooks above.
#
# ==== Options
#
# The first and last part used to find the generator to be invoked are
# guessed based on class invokes hook_for, as noticed in the example above.
# This can be customized with two options: :in and :as.
#
# Let's suppose you are creating a generator that needs to invoke the
# controller generator from test unit. Your first attempt is:
#
# class AwesomeGenerator < Rails::Generators::Base
# hook_for :test_framework
# end
#
# The lookup in this case for test_unit as input is:
#
# "test_unit:awesome", "test_unit"
#
# Which is not the desired lookup. You can change it by providing the
# :as option:
#
# class AwesomeGenerator < Rails::Generators::Base
# hook_for :test_framework, as: :controller
# end
#
# And now it will look up at:
#
# "test_unit:controller", "test_unit"
#
# Similarly, if you want it to also look up in the rails namespace, you
# just need to provide the :in value:
#
# class AwesomeGenerator < Rails::Generators::Base
# hook_for :test_framework, in: :rails, as: :controller
# end
#
# And the lookup is exactly the same as previously:
#
# "rails:test_unit", "test_unit:controller", "test_unit"
#
# ==== Switches
#
# All hooks come with switches for user interface. If you do not want
# to use any test framework, you can do:
#
# rails generate controller Account --skip-test-framework
#
# Or similarly:
#
# rails generate controller Account --no-test-framework
#
# ==== Boolean hooks
#
# In some cases, you may want to provide a boolean hook. For example, webrat
# developers might want to have webrat available on controller generator.
# This can be achieved as:
#
# Rails::Generators::ControllerGenerator.hook_for :webrat, type: :boolean
#
# Then, if you want webrat to be invoked, just supply:
#
# rails generate controller Account --webrat
#
# The hooks lookup is similar as above:
#
# "rails:generators:webrat", "webrat:generators:controller", "webrat"
#
# ==== Custom invocations
#
# You can also supply a block to hook_for to customize how the hook is
# going to be invoked. The block receives two arguments, an instance
# of the current class and the class to be invoked.
#
# For example, in the resource generator, the controller should be invoked
# with a pluralized class name. But by default it is invoked with the same
# name as the resource generator, which is singular. To change this, we
# can give a block to customize how the controller can be invoked.
#
# hook_for :resource_controller do |instance, controller|
# instance.invoke controller, [ instance.name.pluralize ]
# end
#
def self.hook_for(*names, &block)
options = names.extract_options!
in_base = options.delete(:in) || base_name
as_hook = options.delete(:as) || generator_name
names.each do |name|
unless class_options.key?(name)
defaults = if options[:type] == :boolean
{}
elsif [true, false].include?(default_value_for_option(name, options))
{ banner: "" }
else
{ desc: "#{name.to_s.humanize} to be invoked", banner: "NAME" }
end
class_option(name, defaults.merge!(options))
end
hooks[name] = [ in_base, as_hook ]
invoke_from_option(name, options, &block)
end
end
```
```
# .bundle/ruby/2.2.0/gems/thor-0.19.4/lib/thor/parser/option.rb:113:in `validate!'
# parse :foo => true
# #=> Option foo with default value true and type boolean
#
# The valid types are :boolean, :numeric, :hash, :array and :string. If none
# is given a default type is assumed. This default type accepts arguments as
# string (--foo=value) or booleans (just --foo).
#
# By default all options are optional, unless :required is given.
def validate_default_type!
default_type = case @default
when nil
return
when TrueClass, FalseClass
required? ? :string : :boolean
when Numeric
:numeric
when Symbol
:string
when Hash, Array, String
@default.class.name.downcase.to_sym
end
# TODO: This should raise an ArgumentError in a future version of Thor
if default_type != @type
warn "Expected #{@type} default value for '#{switch_name}'; got #{@default.inspect} (#{default_type})"
end
end
```
```
go get -u github.com/client9/misspell/cmd/misspell
misspell -w -q -error -source=text {app,config,lib,test}/**/*
```
> workers = flag.Int("j", 0, "Number of workers, 0 = number of CPUs")
> writeit = flag.Bool("w", false, "Overwrite file with corrections (default is just to display)")
> quietFlag = flag.Bool("q", false, "Do not emit misspelling output")
> outFlag = flag.String("o", "stdout", "output file or [stderr|stdout|]")
> format = flag.String("f", "", "'csv', 'sqlite3' or custom Golang template for output")
> ignores = flag.String("i", "", "ignore the following corrections, comma separated")
> locale = flag.String("locale", "", "Correct spellings using locale perferances for US or UK. Default is to use a neutral variety of English. Setting locale to US will correct the British spelling of 'colour' to 'color'")
> mode = flag.String("source", "auto", "Source mode: auto=guess, go=golang source, text=plain or markdown-like text")
> debugFlag = flag.Bool("debug", false, "Debug matching, very slow")
> exitError = flag.Bool("error", false, "Exit with 2 if misspelling found")
* This adds namespace lookup to serializer_for
* address rubocop issue
* address @bf4's feedback
* add docs
* update docs, add more tests
* apparently rails master doesn't have before filter
* try to address serializer cache issue between tests
* update cache for serializer lookup to include namespace in the key, and fix the tests for explicit namespace
* update docs, and use better cache key creation method
* update docs [ci skip]
* update docs [ci skip]
* add to changelog [ci skip]
For JSONAPI, `include_data` currently means, "should we populate the
'data'" key for this relationship. Current options are true/false.
This adds the `:if_sideloaded` option. This means "only
populate the 'data' key when we are sideloading this relationship." This
is because 'data' is often only relevant to sideloading, and causes a
database hit.
Addresses https://github.com/rails-api/active_model_serializers/issues/1555
If you specify include_data false, and do not have any links for this
relationship, we would output something like:
`{ relationships: { comments: {} } }`
This is not valid jsonapi. We will now render
`{ relationships: { comments: { meta: {} } } }`
Instead.
Relevant jsonapi spec: http://jsonapi.org/format/#document-resource-object-relationships
* Make assocations asserts easier to understand
* Refactor Association into Field like everything else
* Make assocation serializer/links/meta lazier
* Push association deeper into relationship
* Simplify association usage in relationships
* Better naming of reflection parent serializer
* Easier to read association method
The `:attributes` adapter is the default one, but it did not support
key transformation. This was very surprising behavior, since the
"Configuration Options" page in the guides didn't mention that this
behavior was not supported by the attributes adapter.
This commit adds key transform support to the attributes adapter, and
adds documentation about the default transform for the attributes
adapter (which is `:unaltered`).
This commit also handles arrays when transforming keys, which was needed
in the case where you're serializing a collection with the Attributes
adapter. With the JSON adapter, it was always guaranteed to pass a hash
to the KeyTransform functions because of the top-level key. Since there
is no top-level key for the Attributes adapter, the return value could
be an array.
* replace reflection collection type with hash to prevent duplicated associations in some cases
* include tests
* Fix robucup offenses
* Improve test
* Remove usless requirement
* improve tests
* remove custom_options option from Post and InheritedPost serializer
* Improve tests
* update changelog
* update changelog
Fix code-styling issues from .rubocop_todo.yml
* re: RuboCop: Bulk minor style corrections
* re: RuboCop - hash indention corrections
* re: RuboCop - replace rocket style hashes
* re: RuboCop - get rid of redundant curly braces around a hash parameter
* re: RuboCop - Align the elements of a hash literal if they span more than one line.
* re: RuboCop - Use nested module/class definition instead of compact style.
* re: RuboCop - Suppress of handling LoadError for optional dependencies
* re: RuboCop - use include_ prefix instead of has_
* re: RuboCop - Disable Style/PredicateName rule for public API methods
* re: RuboCop - Remove empty .rubocop_todo.yml
* re: RuboCop - replace rocket style hashes
* Fix#1759, Grape integration, adds serialization_context
- `serialization_context` is added in grape formatter so grape continues to render models without an explicit call to the `render` helper method
- Made it straightforward for subclasses to add other serializer options (such as `serialization_scope`).
* Updated Grape tests to include:
- paginated collections
- implicit Grape serializer (i.e. without explicit invocation of `render` helper method)
* Update Changelog with fixes.
- improves improves serialization_context to take options and not depend
on a `request` object.
- adds descriptive error on missing serialization_context.
- Document overriding `CollectionSerializer#paginated?`.
These errors are breaking the build, which seems to use RuboCop 0.40 [1]
despite the Gemfile.lock pinning rubocop to 0.38.
New lints that I am updating the code style to reflect:
- Style/EmptyCaseCondition: Do not use empty case condition, instead use
an if expression.
- Style/MultilineArrayBraceLayout: Closing array brace must be on the
same line as the last array element when opening brace is on the same
line as the first array element.
- Style/MultilineHashBraceLayout: Closing hash brace must be on the same
line as the last hash element when opening brace is on the same line
as the first hash element.
- Style/MultilineMethodCallBraceLayout: Closing method call brace must
be on the line after the last argument when opening brace is on a
separate line from the first argument.
[1] https://github.com/bbatsov/rubocop/releases/tag/v0.40.0
This is useful to set application-wide default behavior - e.g. in
previous versions of AMS the default behavior was to serialize the
full object graph by default - equivalent to the '**' include tree.
Currently just the global setting, but I think this could also work
on a per-serializer basis, with more attention.