gems_generator 0.1.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. checksums.yaml +4 -4
  2. data/.gitignore +1 -1
  3. data/.rspec_status +25 -0
  4. data/README.md +21 -4
  5. data/lib/gems_generator/version.rb +1 -1
  6. data/lib/gems_generator.rb +1 -0
  7. data/lib/generators/gems_generator/config/gitignore_generator.rb +20 -0
  8. data/lib/generators/gems_generator/grape/init_generator.rb +85 -0
  9. data/lib/generators/gems_generator/grape/templates/base_api.rb.erb +21 -0
  10. data/lib/generators/gems_generator/grape/templates/concerns/api_exception_handler.rb +17 -0
  11. data/lib/generators/gems_generator/grape/templates/concerns/document_handler.rb +15 -0
  12. data/lib/generators/gems_generator/grape/templates/concerns/ping_pong.rb +11 -0
  13. data/lib/generators/gems_generator/grape/templates/concerns/request_logger.rb +17 -0
  14. data/lib/generators/gems_generator/grape/templates/initializers/rack-attack.rb +79 -0
  15. data/lib/generators/gems_generator/grape/templates/initializers/swagger.rb +25 -0
  16. data/lib/generators/gems_generator/grape/templates/lib/api_error.rb +73 -0
  17. data/lib/generators/gems_generator/grape/templates/locales/api_error/en.yml +27 -0
  18. data/lib/generators/gems_generator/lograge/init_generator.rb +18 -0
  19. data/lib/generators/gems_generator/lograge/templates/lograge.rb +21 -0
  20. data/lib/generators/gems_generator/rspec/init_generator.rb +46 -0
  21. data/lib/generators/gems_generator/rspec/templates/external_api_mock.rb +10 -0
  22. data/lib/generators/gems_generator/rspec/templates/rails_helper.rb +80 -0
  23. data/lib/generators/gems_generator/rspec/templates/shoulda_matchers.rb +12 -0
  24. data/lib/generators/gems_generator/rspec/templates/spec_helper.rb +99 -0
  25. data/lib/generators/gems_generator/rspec/templates/support/helpers/json_response.rb +27 -0
  26. data/lib/generators/gems_generator/rspec/templates/support/helpers.rb +6 -0
  27. data/lib/generators/gems_generator/rspec/templates/support/message_delivery.rb +6 -0
  28. data/lib/generators/gems_generator/rspec/templates/support/shared_contexts/example_shared_context.rb +3 -0
  29. data/lib/generators/gems_generator/rspec/templates/support/shared_examples/example_shared_example.rb +3 -0
  30. metadata +26 -5
  31. data/gems_generator-0.1.0.gem +0 -0
  32. data/lib/generators/install_generator.rb +0 -14
  33. data/lib/generators/templates/test.rb +0 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 0efa120e6ad37afedb8238d8145b071530ce91bb
4
- data.tar.gz: f9f1ee4b27acef39b58d46a4576e65af8cdfa300
3
+ metadata.gz: 7d0dc96c0c88cae9064f7fcbd0e47d3888a3cf3d
4
+ data.tar.gz: 9f3f84ac6dc6a17e2c87cf3e3dc71187d60bcbc5
5
5
  SHA512:
6
- metadata.gz: dd3d5de5b6b4320c63866acde921b26e2d3346bdb93dd3af06606574d343366234a223656527463653f630c11934b7a49467254a442e96816dd16adbbc394200
7
- data.tar.gz: 00f81d7645564de2f8698d9f260b90e9303122f2a58513f104946bf688f1ebeaf6416134df2141a6803c1076e3eb7cc85eec4dd74730f099480149e82bbd15f5
6
+ metadata.gz: 1e7b9eb34a40279a082e6eebf9be49a2968f51458c4b6033affae06279fda78b39a71634de43cde3b1ca0ccf5f4901086a1a1a47c1e4740017096b539a26d14c
7
+ data.tar.gz: e89736eca390884242b59043e937c74f455d3845325406cba9e844b99a24e046d942189f193535b83ee2592b1d391c0ee0abbe642220d085d905cc6fb1be6aea
data/.gitignore CHANGED
@@ -9,4 +9,4 @@
9
9
  /tmp/
10
10
 
11
11
  # rspec failure tracking
12
- .rspec_status
12
+ # .rspec_status
data/.rspec_status ADDED
@@ -0,0 +1,25 @@
1
+ example_id | status | run_time |
2
+ --------------------------------------------------------- | ------ | --------------- |
3
+ ./spec/gems_generator_spec.rb[1:1] | passed | 0.00055 seconds |
4
+ ./spec/gems_generator_spec.rb[1:2] | failed | 0.0134 seconds |
5
+ ./spec/generators/config/gitignore_spec.rb[1:1:1:1] | passed | 0.00206 seconds |
6
+ ./spec/generators/grape/init_generator_spec.rb[1:1:1:1] | passed | 0.00101 seconds |
7
+ ./spec/generators/grape/init_generator_spec.rb[1:2:1:1] | passed | 0.00016 seconds |
8
+ ./spec/generators/grape/init_generator_spec.rb[1:2:1:2] | passed | 0.00016 seconds |
9
+ ./spec/generators/grape/init_generator_spec.rb[1:3:1:1] | passed | 0.00012 seconds |
10
+ ./spec/generators/grape/init_generator_spec.rb[1:3:2:1] | passed | 0.00022 seconds |
11
+ ./spec/generators/grape/init_generator_spec.rb[1:3:3:1] | passed | 0.0002 seconds |
12
+ ./spec/generators/grape/init_generator_spec.rb[1:3:4:1] | passed | 0.00014 seconds |
13
+ ./spec/generators/grape/init_generator_spec.rb[1:4:1:1] | passed | 0.00017 seconds |
14
+ ./spec/generators/grape/init_generator_spec.rb[1:5:1:1] | passed | 0.00013 seconds |
15
+ ./spec/generators/grape/init_generator_spec.rb[1:6:1:1] | passed | 0.00012 seconds |
16
+ ./spec/generators/grape/init_generator_spec.rb[1:7:1:1] | passed | 0.00012 seconds |
17
+ ./spec/generators/grape/init_generator_spec.rb[1:7:2:1] | passed | 0.00014 seconds |
18
+ ./spec/generators/grape/init_generator_spec.rb[1:8:1:1] | passed | 30.38 seconds |
19
+ ./spec/generators/lograge/init_generator_spec.rb[1:1:1:1] | passed | 0.00018 seconds |
20
+ ./spec/generators/rspec/init_generator_spec.rb[1:1:1:1] | passed | 0.00022 seconds |
21
+ ./spec/generators/rspec/init_generator_spec.rb[1:2:1:1] | passed | 0.00013 seconds |
22
+ ./spec/generators/rspec/init_generator_spec.rb[1:3:1:1] | passed | 0.00014 seconds |
23
+ ./spec/generators/rspec/init_generator_spec.rb[1:4:1:1] | passed | 0.00014 seconds |
24
+ ./spec/generators/rspec/init_generator_spec.rb[1:5:1:1] | passed | 0.0001 seconds |
25
+ ./spec/generators/rspec/init_generator_spec.rb[1:6:1:1] | passed | 0.0001 seconds |
data/README.md CHANGED
@@ -16,13 +16,30 @@ And then execute:
16
16
 
17
17
  $ bundle
18
18
 
19
- Or install it yourself as:
19
+ ## Usage
20
20
 
21
- $ gem install gems_generator
21
+ Install relevant rspec gems:
22
+ ```ruby
23
+ rails generate gems_generator:rspec:init YourProjectName
24
+ ```
22
25
 
23
- ## Usage
26
+ Install relevant grape gems:
27
+ ```ruby
28
+ rails generate gems_generator:grape:init
29
+ ```
24
30
 
25
- TODO: Write usage instructions here
31
+ Install config gems:
32
+ ```ruby
33
+ #Gemfile
34
+ gem 'config'
35
+ #console
36
+ bundle install
37
+ rails generate config:install
38
+ ```
39
+
40
+ Config gitignore
41
+ ```
42
+ ```
26
43
 
27
44
  ## Development
28
45
 
@@ -1,3 +1,3 @@
1
1
  module GemsGenerator
2
- VERSION = "0.1.1"
2
+ VERSION = "1.0.0"
3
3
  end
@@ -1,4 +1,5 @@
1
1
  require "gems_generator/version"
2
+ require "gems_generator/engine"
2
3
  require "rails"
3
4
 
4
5
  module GemsGenerator
@@ -0,0 +1,20 @@
1
+ module GemsGenerator
2
+ module Config
3
+ module Generators
4
+ class GitignoreGenerator < ::Rails::Generators::Base
5
+ source_root File.expand_path("../templates", __FILE__)
6
+
7
+ def insert_gitignore
8
+ append_to_file ".gitignore" do
9
+ "\ncoverage\n" +
10
+ "config/database.yml\n" +
11
+ "config/settings.local.yml\n" +
12
+ "config/settings/*.local.yml\n" +
13
+ "config/environments/*.local.yml\n" +
14
+ "config/database.yml\n"
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,85 @@
1
+ module GemsGenerator
2
+ module Grape
3
+ module Generators
4
+ class InitGenerator < ::Rails::Generators::NamedBase
5
+ source_root File.expand_path("../templates", __FILE__)
6
+
7
+ desc "Add relevant gems: grape,grape_logging, grape_on_rails_routes, grape-swagger"
8
+ def add_gems
9
+ gem "grape", '~>0.15.0'
10
+ gem "grape_logging", git: "git@github.com:aserafin/grape_logging.git"
11
+ gem "grape_on_rails_routes"
12
+ gem_group :development, :staging, :test do
13
+ gem "grape-swagger"
14
+ gem "grape-swagger-rails", git: "git@github.com:ruby-grape/grape-swagger-rails.git"
15
+ end
16
+ gem 'rack-attack'
17
+ end
18
+
19
+ desc "Create BaseApi "
20
+ def copy_base_api_rb
21
+ template "base_api.rb.erb", File.join('app/api/',"#{file_name}_api.rb")
22
+ end
23
+
24
+ desc "Create Concerns File"
25
+ def copy_concerns_file
26
+ api_exception_handler_path = "concerns/api_exception_handler.rb"
27
+ template api_exception_handler_path, File.join('app/api/', api_exception_handler_path)
28
+
29
+ document_handler_path = "concerns/document_handler.rb"
30
+ template document_handler_path, File.join('app/api/', document_handler_path)
31
+
32
+ ping_pong_path = "concerns/ping_pong.rb"
33
+ template ping_pong_path, File.join('app/api/', ping_pong_path)
34
+
35
+ request_logger_path = "concerns/request_logger.rb"
36
+ template request_logger_path, File.join('app/api/', request_logger_path)
37
+ end
38
+
39
+ desc "Add Grape Routes"
40
+ def insert_grape_routes
41
+ route "mount #{class_name}API => '/'"
42
+ end
43
+
44
+ desc "insert Grape Swagger Routes"
45
+ def insert_grape_swagger_routes
46
+ route "mount GrapeSwaggerRails::Engine => '/swagger' unless Rails.env.production?"
47
+ end
48
+
49
+ desc "Create Swagger Config File"
50
+ def copy_swagger_file
51
+ swagger_path = "config/initializers/swagger.rb"
52
+ template "initializers/swagger.rb", swagger_path
53
+ end
54
+
55
+ desc "Create ApiError Lib File"
56
+ def cope_api_error_file
57
+ template "lib/api_error.rb", "lib/api_error.rb"
58
+ template "locales/api_error/en.yml", "config/locales/api_error/en.yml"
59
+ end
60
+
61
+ desc "Rack Attack config file"
62
+ def create_rack_attack_rb
63
+ template "initializers/rack-attack.rb", "config/initializers/rack-attack.rb"
64
+ end
65
+
66
+ desc "Insert auload_paths and eager_load_paths to application"
67
+ def insert_application_rb
68
+ inject_into_file "config/application.rb", after: "Rails::Application\n" do
69
+ " config.autoload_paths << Rails.root.join('lib')\n" +
70
+ " config.eager_load_paths << Rails.root.join('lib')\n"
71
+ end
72
+
73
+
74
+ inject_into_file "config/application.rb", after: "Rails::Application\n" do
75
+ " config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**/*.{rb,yml}').to_s]\n" +
76
+ " config.i18n.available_locales = %w(en zh-CN kr ja)\n" +
77
+ " config.i18n.fallbacks = [:en]\n"
78
+ end
79
+
80
+ end
81
+
82
+ end
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,21 @@
1
+ class <%= class_name %>API < Grape::API
2
+ #提供默认的攻击防护,如限制ip的访问量等,配置文件在config/initializers/rack-attack.rb
3
+ use Rack::Attack if Rails.env.production?
4
+
5
+ include Concerns::PingPong
6
+ include Concerns::RequestLogger
7
+ include Concerns::ApiExceptionHandler
8
+
9
+ default_format :json
10
+ format :json
11
+ prefix :api
12
+
13
+ helpers do
14
+ def declared_params
15
+ declared(params, include_missing: false)
16
+ end
17
+ end
18
+
19
+ #swagger
20
+ include Concerns::DocumentHandler
21
+ end
@@ -0,0 +1,17 @@
1
+ module Concerns
2
+ module ApiExceptionHandler
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ rescue_from ApiError do |exception|
7
+ Rails.logger.info "[BaseApi Error] #{exception.status}"
8
+ # headers['content-type'] = 'application/json'
9
+ Rack::Response.new({status: exception.show_code, msg: exception.message}.to_json, 200, { 'Content-Type' => 'application/json' })
10
+ end
11
+
12
+ rescue_from Grape::Exceptions::ValidationErrors do |e|
13
+ error! ({status: 103, msg: 'params invalid'})
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,15 @@
1
+ module Concerns
2
+ module DocumentHandler
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ if Rails.env.development? or Rails.env.staging?
7
+ add_swagger_documentation(
8
+ mount_path: '/docs',
9
+ base_path: '/',
10
+ hide_format: true
11
+ )
12
+ end
13
+ end
14
+ end
15
+ end
@@ -0,0 +1,11 @@
1
+ module Concerns
2
+ module PingPong
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ get 'ping' do
7
+ 'pong'
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,17 @@
1
+ module Concerns
2
+ module RequestLogger
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ logger.formatter = GrapeLogging::Formatters::Default.new
7
+
8
+ use GrapeLogging::Middleware::RequestLogger,
9
+ logger: logger,
10
+ instrumentation_key: 'grape_key',
11
+ include: [
12
+ GrapeLogging::Loggers::Response.new,
13
+ GrapeLogging::Loggers::FilterParameters.new
14
+ ]
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,79 @@
1
+ class Rack::Attack
2
+
3
+ ### Configure Cache ###
4
+
5
+ # If you don't want to use Rails.cache (Rack::Attack's default), then
6
+ # configure it here.
7
+ #
8
+ # Note: The store is only used for throttling (not blacklisting and
9
+ # whitelisting). It must implement .increment and .write like
10
+ # ActiveSupport::Cache::Store
11
+
12
+ # Rack::Attack.cache.store = ActiveSupport::Cache::MemoryStore.new
13
+
14
+ ### Throttle Spammy Clients ###
15
+
16
+ # If any single client IP is making tons of requests, then they're
17
+ # probably malicious or a poorly-configured scraper. Either way, they
18
+ # don't deserve to hog all of the app server's CPU. Cut them off!
19
+ #
20
+ # Note: If you're serving assets through rack, those requests may be
21
+ # counted by rack-attack and this throttle may be activated too
22
+ # quickly. If so, enable the condition to exclude them from tracking.
23
+
24
+ # Throttle all requests by IP (60rpm)
25
+ #
26
+ # Key: "rack::attack:#{Time.now.to_i/:period}:req/ip:#{req.ip}"
27
+ throttle('req/ip', :limit => 300, :period => 5.minutes) do |req|
28
+ req.ip # unless req.path.start_with?('/assets')
29
+ end
30
+
31
+ ### Prevent Brute-Force Login Attacks ###
32
+
33
+ # The most common brute-force login attack is a brute-force password
34
+ # attack where an attacker simply tries a large number of emails and
35
+ # passwords to see if any credentials match.
36
+ #
37
+ # Another common method of attack is to use a swarm of computers with
38
+ # different IPs to try brute-forcing a password for a specific account.
39
+
40
+ # Throttle POST requests to /login by IP address
41
+ #
42
+ # Key: "rack::attack:#{Time.now.to_i/:period}:logins/ip:#{req.ip}"
43
+ =begin
44
+ throttle('logins/ip', :limit => 5, :period => 20.seconds) do |req|
45
+ if req.path == '/login' && req.post?
46
+ req.ip
47
+ end
48
+ end
49
+ =end
50
+ # Throttle POST requests to /login by email param
51
+ #
52
+ # Key: "rack::attack:#{Time.now.to_i/:period}:logins/email:#{req.email}"
53
+ #
54
+ # Note: This creates a problem where a malicious user could intentionally
55
+ # throttle logins for another user and force their login requests to be
56
+ # denied, but that's not very common and shouldn't happen to you. (Knock
57
+ # on wood!)
58
+ =begin
59
+ throttle("logins/email", :limit => 5, :period => 20.seconds) do |req|
60
+ if req.path == '/login' && req.post?
61
+ # return the email if present, nil otherwise
62
+ req.params['email'].presence
63
+ end
64
+ end
65
+ =end
66
+ ### Custom Throttle Response ###
67
+
68
+ # By default, Rack::Attack returns an HTTP 429 for throttled responses,
69
+ # which is just fine.
70
+ #
71
+ # If you want to return 503 so that the attacker might be fooled into
72
+ # believing that they've successfully broken your app (or you just want to
73
+ # customize the response), then uncomment these lines.
74
+ # self.throttled_response = lambda do |env|
75
+ # [ 503, # status
76
+ # {}, # headers
77
+ # ['']] # body
78
+ # end
79
+ end
@@ -0,0 +1,25 @@
1
+ if Rails.env.development? or Rails.env.staging?
2
+ GrapeSwaggerRails.options.url = '/api/docs'
3
+ GrapeSwaggerRails.options.app_name = '项目文档'
4
+
5
+
6
+ GrapeSwaggerRails.options.before_action do
7
+ GrapeSwaggerRails.options.app_url = request.protocol + request.host_with_port
8
+ end
9
+
10
+ if Rails.env.staging?
11
+ module GrapeSwaggerRails
12
+ module HttpBaseAuth
13
+ extend ActiveSupport::Concern
14
+
15
+ included do
16
+ #如果安装了configgem包,取消掉注释,并且设定相应的值
17
+ #http_basic_authenticate_with name: Settings.swagger.name, password: Settings.swagger.password
18
+ http_basic_authenticate_with name: "rails_swagger", password: "rails_swagger"
19
+ end
20
+ end
21
+ end
22
+
23
+ GrapeSwaggerRails::ApplicationController.send :include, GrapeSwaggerRails::HttpBaseAuth
24
+ end
25
+ end
@@ -0,0 +1,73 @@
1
+ class ApiError < StandardError
2
+ attr_accessor :module_name, :status, :params
3
+
4
+ # 初始化 ApiError
5
+ #
6
+ # @param args [*Array] 1..3 可变长度的参数列表,对应以下三种参数列表
7
+ # 1. (status, options = {})
8
+ # 2. (module_name, status, options = {})
9
+ #
10
+ # @param module_name [Symbol, String] 模块名, e.x. `:dealer`
11
+ # @param status [Symbol, String] 状态名,e.x. `:login_failed`
12
+ # @param options [Hash] 传递给底层 I18n 的 options,比如针对如下翻译:
13
+ # error: "Error: %{additional_message}"
14
+ #
15
+ # 则可以使用:
16
+ # ApiError.new(:error, additional_message: "Something went wrong").message
17
+ # => "Error: Something went wrong"
18
+ #
19
+ def initialize(*args)
20
+ @params = args.extract_options!
21
+ @module_name, @status = args.map(&:to_s)
22
+ @module_name, @status = "special", @module_name unless @status.present?
23
+ Rails.logger.info message
24
+ validates!
25
+ end
26
+
27
+ def show_code
28
+ code = I18n.t("dji_errors.#{module_name}.#{status}.code")
29
+
30
+ if module_name == "special"
31
+ code.to_i
32
+ else
33
+ "1#{module_code}#{code}".to_i
34
+ end
35
+ end
36
+
37
+ def message
38
+ I18n.t( "dji_errors.#{module_name}.#{status}.message", params )
39
+ end
40
+
41
+ private
42
+ def module_code
43
+ I18n.t("dji_errors.#{module_name}.module_code")
44
+ end
45
+
46
+ def status_definitions
47
+ return @status_definitions if @status_definitions.present?
48
+ @status_definitions ||= module_definitions[status.to_sym]
49
+ raise ApiError::UnknownCode unless @status_definitions.is_a?(Hash)
50
+
51
+ @status_definitions
52
+ end
53
+
54
+ def validates!
55
+ check_module_name && check_status
56
+ end
57
+
58
+ def check_module_name
59
+ I18n.t("dji_errors.#{module_name}.module_code", raise: true)
60
+ rescue I18n::MissingTranslationData => e
61
+ raise ApiError::UnknownModuleName.new(e.message)
62
+ end
63
+
64
+ def check_status
65
+ I18n.t("dji_errors.#{module_name}.#{status}.code", raise: true)
66
+ I18n.t("dji_errors.#{module_name}.#{status}.message", raise: true)
67
+ rescue I18n::MissingTranslationData => e
68
+ raise ApiError::UnknownCode.new(e.message)
69
+ end
70
+ end
71
+
72
+ class ApiError::UnknownModuleName < StandardError;end
73
+ class ApiError::UnknownCode < StandardError;end
@@ -0,0 +1,27 @@
1
+ # errors 提供基于 ApiError 的状态码以及错误消息支持
2
+ #
3
+ # 结构说明:
4
+ # 模块名称:
5
+ # module_code: 2位模块码 # (module_code 仅需要在 en.yml 中声明即可,其他语言文件不需要)
6
+ # 状态名称:
7
+ # code: 该模块下的3位状态码 # (code 仅需要在 en.yml 中声明即可,其他语言文件不需要)
8
+ # message: 错误信息翻译
9
+ #
10
+ # 注意:所有错误状态码及其消息翻译严格遵守上述格式!
11
+ #
12
+ #en:
13
+ # api_errors:
14
+ # special:
15
+ # module_code: ""
16
+ # unauthenticated:
17
+ # code: "401"
18
+ # message: "Need Authentication!"
19
+ # forbidden:
20
+ # code: "403"
21
+ # message: "Reject!"
22
+ # timestamp_error:
23
+ # code: "102"
24
+ # message: "Timestamp error."
25
+ # params_invalid:
26
+ # code: "103"
27
+ # message: "Params invalid."
@@ -0,0 +1,18 @@
1
+ module GemsGenerator
2
+ module Lograge
3
+ module Generators
4
+ class InitGenerator < ::Rails::Generators::Base
5
+ source_root File.expand_path("../templates", __FILE__)
6
+
7
+ def insert_gems
8
+ gem 'lograge'
9
+ gem 'logstash-event'
10
+ end
11
+
12
+ def create_config_file
13
+ template "lograge.rb", "config/initializers/lograge.rb"
14
+ end
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,21 @@
1
+ Rails.application.configure do
2
+
3
+ # 开发环境下仍然需要了解详细的 Rails 日志
4
+ config.lograge.keep_original_rails_log = true if Rails.env.development?
5
+ #config.lograge.logger = ActiveSupport::Logger.new "#{Rails.root}/log/lograge_#{Rails.env}.log"
6
+
7
+ config.lograge.enabled = true unless Rails.env.development?
8
+
9
+ #配置感兴趣的参数输出, 剔除controller和action的信息
10
+ config.lograge.custom_options = lambda do |event|
11
+ params = event.payload[:params].reject do |k|
12
+ %w(controller action).include? k
13
+ end
14
+ {
15
+ ip: event.payload[:ip],
16
+ time: event.time.to_s(:standard),
17
+ params: params
18
+ }
19
+ end
20
+ config.lograge.formatter = Lograge::Formatters::Logstash.new
21
+ end
@@ -0,0 +1,46 @@
1
+ module GemsGenerator
2
+ module Rspec
3
+ module Generators
4
+ class InitGenerator < ::Rails::Generators::Base
5
+ source_root File.expand_path("../templates", __FILE__)
6
+
7
+ def insert_gems
8
+ gem_group :test do
9
+ gem 'simplecov', :require => false
10
+ gem "rspec-rails"
11
+ gem 'rails-controller-testing'
12
+ gem "rspec-mocks"
13
+ gem "factory_girl_rails"
14
+ gem 'shoulda-matchers', '~> 3.1', '>= 3.1.1'
15
+ gem 'webmock'
16
+ gem 'database_cleaner', '~> 1.5', '>= 1.5.3'
17
+ end
18
+ end
19
+
20
+ def create_rails_helper_rb
21
+ template "rails_helper.rb", "spec/rails_helper.rb"
22
+ end
23
+
24
+ def create_spec_helper_rb
25
+ template "spec_helper.rb", "spec/spec_helper.rb"
26
+ end
27
+
28
+ def create_shoulda_matchers_rb
29
+ template "shoulda_matchers.rb", "spec/shoulda_matchers.rb"
30
+ end
31
+
32
+ def create_external_api_mock_rb
33
+ template "external_api_mock.rb", "spec/external_api_mock.rb"
34
+ end
35
+
36
+ def create_support_dir
37
+ directory "support/", "spec/support/"
38
+ end
39
+
40
+ def create_factories_dir
41
+ directory "factories/", "spec/factories/"
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,10 @@
1
+ require 'webmock/rspec'
2
+ RSpec.configure do |config|
3
+ #若允许进行真实的http调用,则取消注释
4
+ #WebMock.allow_net_connect!(net_http_connect_on_start: true)
5
+ config.before(:each) do
6
+ #在里面mock函数
7
+ #Doc url: https://github.com/bblimke/webmock
8
+ end
9
+ end
10
+
@@ -0,0 +1,80 @@
1
+ # This file is copied to spec/ when you run 'rails generate rspec:install'
2
+ require 'simplecov'
3
+ SimpleCov.start 'rails'
4
+ require 'pry'
5
+ ENV['RAILS_ENV'] ||= 'test'
6
+ require File.expand_path('../../config/environment', __FILE__)
7
+ # Prevent database truncation if the environment is production
8
+ abort("The Rails environment is running in production mode!") if Rails.env.production?
9
+ require 'spec_helper'
10
+ require 'rspec/rails'
11
+ require 'shoulda_matchers'
12
+ require 'external_api_mock'
13
+ # Add additional requires below this line. Rails is not loaded until this point!
14
+
15
+ # Requires supporting ruby files with custom matchers and macros, etc, in
16
+ # spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
17
+ # run as spec files by default. This means that files in spec/support that end
18
+ # in _spec.rb will both be required and run as specs, causing the specs to be
19
+ # run twice. It is recommended that you do not name files matching this glob to
20
+ # end with _spec.rb. You can configure this pattern with the --pattern
21
+ # option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
22
+ #
23
+ # The following line is provided for convenience purposes. It has the downside
24
+ # of increasing the boot-up time by auto-requiring all files in the support
25
+ # directory. Alternatively, in the individual `*_spec.rb` files, manually
26
+ # require only the support files necessary.
27
+ #
28
+ Dir[Rails.root.join('spec/support/**/*.rb')].each { |f| require f }
29
+
30
+ # Checks for pending migration and applies them before tests are run.
31
+ # If you are not using ActiveRecord, you can remove this line.
32
+ ActiveRecord::Migration.maintain_test_schema!
33
+
34
+ RSpec.configure do |config|
35
+ # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
36
+ config.fixture_path = "#{::Rails.root}/spec/fixtures"
37
+
38
+ config.include Helpers
39
+
40
+ # If you're not using ActiveRecord, or you'd prefer not to run each of your
41
+ # examples within a transaction, remove the following line or assign false
42
+ # instead of true.
43
+ config.use_transactional_fixtures = true
44
+
45
+ config.include FactoryGirl::Syntax::Methods
46
+ config.include Helpers
47
+ # RSpec Rails can automatically mix in different behaviours to your tests
48
+ # based on their file location, for example enabling you to call `get` and
49
+ # `post` in specs under `spec/controllers`.
50
+ #
51
+ # You can disable this behaviour by removing the line below, and instead
52
+ # explicitly tag your specs with their type, e.g.:
53
+ #
54
+ # RSpec.describe UsersController, :type => :controller do
55
+ # # ...
56
+ # end
57
+ #
58
+ # The different available types are documented in the features, such as in
59
+ # https://relishapp.com/rspec/rspec-rails/docs
60
+ config.infer_spec_type_from_file_location!
61
+
62
+ # Filter lines from Rails gems in backtraces.
63
+ config.filter_rails_from_backtrace!
64
+ # arbitrary gems may also be filtered via:
65
+ # config.filter_gems_from_backtrace("gem name")
66
+ config.before(:suite) do
67
+ DatabaseCleaner.strategy = :transaction
68
+ DatabaseCleaner.clean_with(:truncation)
69
+ end
70
+
71
+ config.around(:each) do |example|
72
+ DatabaseCleaner.cleaning do
73
+ example.run
74
+ end
75
+ end
76
+
77
+ config.before(:each) do
78
+ Rails.cache.clear
79
+ end
80
+ end
@@ -0,0 +1,12 @@
1
+ Shoulda::Matchers.configure do |config|
2
+ config.integrate do |with|
3
+ with.test_framework :rspec
4
+
5
+ # Choose one or more libraries:
6
+ # with.library :active_record
7
+ # with.library :active_model
8
+ # with.library :action_controller
9
+ # Or, choose the following (which implies all of the above):
10
+ with.library :rails
11
+ end
12
+ end
@@ -0,0 +1,99 @@
1
+ # This file was generated by the `rails generate rspec:install` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # The generated `.rspec` file contains `--require spec_helper` which will cause
4
+ # this file to always be loaded, without a need to explicitly require it in any
5
+ # files.
6
+ #
7
+ # Given that it is always loaded, you are encouraged to keep this file as
8
+ # light-weight as possible. Requiring heavyweight dependencies from this file
9
+ # will add to the boot time of your test suite on EVERY test run, even for an
10
+ # individual file that may not need all of that loaded. Instead, consider making
11
+ # a separate helper file that requires the additional dependencies and performs
12
+ # the additional setup, and require it from the spec files that actually need
13
+ # it.
14
+ #
15
+ # The `.rspec` file also contains a few flags that are not defaults but that
16
+ # users commonly want.
17
+ #
18
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
19
+ RSpec.configure do |config|
20
+ # rspec-expectations config goes here. You can use an alternate
21
+ # assertion/expectation library such as wrong or the stdlib/minitest
22
+ # assertions if you prefer.
23
+ config.expect_with :rspec do |expectations|
24
+ # This option will default to `true` in RSpec 4. It makes the `description`
25
+ # and `failure_message` of custom matchers include text for helper methods
26
+ # defined using `chain`, e.g.:
27
+ # be_bigger_than(2).and_smaller_than(4).description
28
+ # # => "be bigger than 2 and smaller than 4"
29
+ # ...rather than:
30
+ # # => "be bigger than 2"
31
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
32
+ end
33
+
34
+ # rspec-mocks config goes here. You can use an alternate test double
35
+ # library (such as bogus or mocha) by changing the `mock_with` option here.
36
+ config.mock_with :rspec do |mocks|
37
+ # Prevents you from mocking or stubbing a method that does not exist on
38
+ # a real object. This is generally recommended, and will default to
39
+ # `true` in RSpec 4.
40
+ mocks.verify_partial_doubles = true
41
+ end
42
+
43
+ # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
44
+ # have no way to turn it off -- the option exists only for backwards
45
+ # compatibility in RSpec 3). It causes shared context metadata to be
46
+ # inherited by the metadata hash of host groups and examples, rather than
47
+ # triggering implicit auto-inclusion in groups with matching metadata.
48
+ config.shared_context_metadata_behavior = :apply_to_host_groups
49
+
50
+ # The settings below are suggested to provide a good initial experience
51
+ # with RSpec, but feel free to customize to your heart's content.
52
+ =begin
53
+ # This allows you to limit a spec run to individual examples or groups
54
+ # you care about by tagging them with `:focus` metadata. When nothing
55
+ # is tagged with `:focus`, all examples get run. RSpec also provides
56
+ # aliases for `it`, `describe`, and `context` that include `:focus`
57
+ # metadata: `fit`, `fdescribe` and `fcontext`, respectively.
58
+ config.filter_run_when_matching :focus
59
+
60
+ # Allows RSpec to persist some state between runs in order to support
61
+ # the `--only-failures` and `--next-failure` CLI options. We recommend
62
+ # you configure your source control system to ignore this file.
63
+ config.example_status_persistence_file_path = "spec/examples.txt"
64
+
65
+ # Limits the available syntax to the non-monkey patched syntax that is
66
+ # recommended. For more details, see:
67
+ # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
68
+ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
69
+ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
70
+ config.disable_monkey_patching!
71
+
72
+ # Many RSpec users commonly either run the entire suite or an individual
73
+ # file, and it's useful to allow more verbose output when running an
74
+ # individual spec file.
75
+ if config.files_to_run.one?
76
+ # Use the documentation formatter for detailed output,
77
+ # unless a formatter has already been configured
78
+ # (e.g. via a command-line flag).
79
+ config.default_formatter = 'doc'
80
+ end
81
+
82
+ # Print the 10 slowest examples and example groups at the
83
+ # end of the spec run, to help surface which specs are running
84
+ # particularly slow.
85
+ config.profile_examples = 10
86
+
87
+ # Run specs in random order to surface order dependencies. If you find an
88
+ # order dependency and want to debug it, you can fix the order by providing
89
+ # the seed, which is printed after each run.
90
+ # --seed 1234
91
+ config.order = :random
92
+
93
+ # Seed global randomization in this process using the `--seed` CLI option.
94
+ # Setting this allows you to use `--seed` to deterministically reproduce
95
+ # test failures related to randomization by passing the same `--seed` value
96
+ # as the one that triggered the failure.
97
+ Kernel.srand config.seed
98
+ =end
99
+ end
@@ -0,0 +1,27 @@
1
+ module Helpers
2
+ module JsonResponse
3
+ extend ActiveSupport::Concern
4
+
5
+ included do
6
+ def json_response
7
+ MultiJson.load(response.body, symbolize_keys: true)
8
+ end
9
+
10
+ def is_success_response
11
+ expect(json_response[:status]).to eq(200)
12
+ end
13
+
14
+ def response_status
15
+ json_response[:status] rescue nil
16
+ end
17
+
18
+ def response_msg
19
+ json_response[:msg] rescue nil
20
+ end
21
+
22
+ def response_data
23
+ json_response[:data] rescue nil
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,6 @@
1
+ module Helpers
2
+ extend ActiveSupport::Concern
3
+ included do
4
+ include JsonResponse
5
+ end
6
+ end
@@ -0,0 +1,6 @@
1
+ #方便mailer类的测试
2
+ class ActionMailer::MessageDelivery
3
+ def deliver_later
4
+ deliver_now
5
+ end
6
+ end
@@ -0,0 +1,3 @@
1
+ RSpec.shared_context "example shared_context" do
2
+ #doc https://relishapp.com/rspec/rspec-core/v/3-6/docs/example-groups/shared-context
3
+ end
@@ -0,0 +1,3 @@
1
+ RSpec.shared_examples "example shared_examples" do |factory|
2
+ #doc https://relishapp.com/rspec/rspec-core/v/3-6/docs/example-groups/shared-examples
3
+ end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: gems_generator
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.1
4
+ version: 1.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - ji.zhang
8
8
  autorequire:
9
9
  bindir: exe
10
10
  cert_chain: []
11
- date: 2017-07-20 00:00:00.000000000 Z
11
+ date: 2017-07-24 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: bundler
@@ -131,6 +131,7 @@ extra_rdoc_files: []
131
131
  files:
132
132
  - ".gitignore"
133
133
  - ".rspec"
134
+ - ".rspec_status"
134
135
  - ".travis.yml"
135
136
  - CODE_OF_CONDUCT.md
136
137
  - Gemfile
@@ -140,13 +141,33 @@ files:
140
141
  - bin/aruba-test-cli
141
142
  - bin/console
142
143
  - bin/setup
143
- - gems_generator-0.1.0.gem
144
144
  - gems_generator.gemspec
145
145
  - lib/gems_generator.rb
146
146
  - lib/gems_generator/engine.rb
147
147
  - lib/gems_generator/version.rb
148
- - lib/generators/install_generator.rb
149
- - lib/generators/templates/test.rb
148
+ - lib/generators/gems_generator/config/gitignore_generator.rb
149
+ - lib/generators/gems_generator/grape/init_generator.rb
150
+ - lib/generators/gems_generator/grape/templates/base_api.rb.erb
151
+ - lib/generators/gems_generator/grape/templates/concerns/api_exception_handler.rb
152
+ - lib/generators/gems_generator/grape/templates/concerns/document_handler.rb
153
+ - lib/generators/gems_generator/grape/templates/concerns/ping_pong.rb
154
+ - lib/generators/gems_generator/grape/templates/concerns/request_logger.rb
155
+ - lib/generators/gems_generator/grape/templates/initializers/rack-attack.rb
156
+ - lib/generators/gems_generator/grape/templates/initializers/swagger.rb
157
+ - lib/generators/gems_generator/grape/templates/lib/api_error.rb
158
+ - lib/generators/gems_generator/grape/templates/locales/api_error/en.yml
159
+ - lib/generators/gems_generator/lograge/init_generator.rb
160
+ - lib/generators/gems_generator/lograge/templates/lograge.rb
161
+ - lib/generators/gems_generator/rspec/init_generator.rb
162
+ - lib/generators/gems_generator/rspec/templates/external_api_mock.rb
163
+ - lib/generators/gems_generator/rspec/templates/rails_helper.rb
164
+ - lib/generators/gems_generator/rspec/templates/shoulda_matchers.rb
165
+ - lib/generators/gems_generator/rspec/templates/spec_helper.rb
166
+ - lib/generators/gems_generator/rspec/templates/support/helpers.rb
167
+ - lib/generators/gems_generator/rspec/templates/support/helpers/json_response.rb
168
+ - lib/generators/gems_generator/rspec/templates/support/message_delivery.rb
169
+ - lib/generators/gems_generator/rspec/templates/support/shared_contexts/example_shared_context.rb
170
+ - lib/generators/gems_generator/rspec/templates/support/shared_examples/example_shared_example.rb
150
171
  homepage: https://github.com/zhangjiha/gems_generator.git
151
172
  licenses:
152
173
  - MIT
Binary file
@@ -1,14 +0,0 @@
1
- require 'rails/generators/named_base'
2
-
3
- module GemsGenerator
4
- module Generators
5
- class InstallGenerator < Rails::Generators::NamedBase
6
- source_root File.expand_path("../templates", __FILE__)
7
-
8
- desc "create test "
9
- def copy_initializer
10
- template "test.rb", File.join('app/uploaders', class_path, "#{file_name}_uploader.rb")
11
- end
12
- end
13
- end
14
- end
@@ -1 +0,0 @@
1
- # Initializer