elocal_api_support 0.1.2 → 0.1.3

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: cdeb546097909b97e80efce4c8312735a3b17ea1
4
- data.tar.gz: eda8b70eecc679af927b2bf35f9e0f78344dc008
3
+ metadata.gz: f99ce80a0db1de44c82bb82b0f063b38515541e6
4
+ data.tar.gz: 9061e4c0dc4c8ae7f1feeb4690b383b17375c4ea
5
5
  SHA512:
6
- metadata.gz: fb7e49521e3468b881e9b63891571641c6e2facd1abc9dcd1dd5ca06c18403ecb760f97783d7a0d2e4c0939ea0728fa572deccce927ca635a52ad67c67d9d474
7
- data.tar.gz: e9fb097ea3ae497a5f5dcc373119aa2fef05d3237555024b9e30759276c7f897a6849ad888576fd1871ca87e812ebafed4f05e8b3debf5259cb6983cd9d4eff1
6
+ metadata.gz: ebd164dfe1a0da8f6bd404e404a6e6a1bc72db089061d8e1d192a1643d6468f1a0b7af7a59df39cbd471847a42a3482f7ca50e7a2ce7cf25aee12ef59397ed29
7
+ data.tar.gz: 94bb8f5b60b36f97e494de02bbe88f45ff93e28326d342d475e85a9d54ae971a39cd2475d3bb009a2fabf4479ca41b3558fd2eb59b5a5c264d09fd31de60aa3c
data/.rubocop.yml ADDED
@@ -0,0 +1,27 @@
1
+ AllCops:
2
+ Include:
3
+ - Rakefile
4
+ Exclude:
5
+ - db/**/*
6
+ - config/**/*
7
+ - script/**/*
8
+ - bin/**/*
9
+ LineLength:
10
+ Enabled: true
11
+ Max: 150
12
+ Documentation:
13
+ Enabled: false
14
+ AlignParameters:
15
+ Enabled: false
16
+ MethodLength:
17
+ Max: 30
18
+ AndOr:
19
+ Enabled: false
20
+ ClassLength:
21
+ Max: 200
22
+ ClassAndModuleChildren:
23
+ Enabled: false
24
+ MultilineOperationIndentation:
25
+ Enabled: false
26
+ Metrics/AbcSize:
27
+ Max: 20
data/Rakefile CHANGED
@@ -1,4 +1,4 @@
1
- require "bundler/gem_tasks"
1
+ require 'bundler/gem_tasks'
2
2
  require 'rake/testtask'
3
3
 
4
4
  Rake::TestTask.new do |t|
@@ -18,13 +18,11 @@ module ElocalApiSupport
18
18
  end
19
19
 
20
20
  module Common
21
-
22
21
  protected
23
22
 
24
23
  def filtered_objects_for_json
25
-
26
24
  if associated_model_serializer
27
- filtered_objects.map{|r| associated_model_serializer.new(r)}
25
+ filtered_objects.map { |r| associated_model_serializer.new(r) }
28
26
  else
29
27
  filtered_objects
30
28
  end
@@ -33,13 +31,14 @@ module ElocalApiSupport
33
31
  def associated_model_serializer
34
32
  unless @associated_model_serializer_lookup_complete
35
33
  c = "#{associated_model}Serializer"
36
- @associated_model_serializer = if Object.const_defined?(c)
37
- Rails.logger.debug("Using #{c}")
38
- c.constantize
39
- else
40
- Rails.logger.debug("No serializer #{c}")
41
- nil
42
- end
34
+ @associated_model_serializer =
35
+ if Object.const_defined?(c)
36
+ Rails.logger.debug("Using #{c}")
37
+ c.constantize
38
+ else
39
+ Rails.logger.debug("No serializer #{c}")
40
+ nil
41
+ end
43
42
  @associated_model_serializer_lookup_complete = true
44
43
  end
45
44
  @associated_model_serializer
@@ -49,6 +48,5 @@ module ElocalApiSupport
49
48
  @model_name ||= controller_name.singularize
50
49
  end
51
50
  end
52
-
53
51
  end
54
- end
52
+ end
@@ -8,9 +8,9 @@ module ElocalApiSupport
8
8
  if obj.save
9
9
  render json: obj
10
10
  else
11
- render json: {errors: obj.errors}, status: 422
11
+ render json: { errors: obj.errors }, status: 422
12
12
  end
13
13
  end
14
14
  end
15
15
  end
16
- end
16
+ end
@@ -5,11 +5,11 @@ module ElocalApiSupport
5
5
  if lookup_object.destroy
6
6
  render json: lookup_object
7
7
  else
8
- render json: {errors: "Failed to destroy #{lookup_object}"}, status: 500
8
+ render json: { errors: "Failed to destroy #{lookup_object}" }, status: 500
9
9
  end
10
10
  rescue ActiveRecord::RecordNotFound
11
11
  render json: {} # record not found is ok for destroy
12
12
  end
13
13
  end
14
14
  end
15
- end
15
+ end
@@ -2,15 +2,56 @@ module ElocalApiSupport
2
2
  module Actions
3
3
  module Index
4
4
  def index
5
+ add_pagination_headers \
6
+ if paginated_request? && paginate_with_headers?
7
+
8
+ render_filtered_objects_as_json
9
+ end
10
+
11
+ protected
12
+
13
+ # Her library likes to paginate with headers,
14
+ # ActiveResource cannot handle headers.
15
+ # So awesomely, two implementations. To use the "Her" implementation with headers
16
+ # this method should be overridend to return true
17
+ def paginate_with_headers?
18
+ false
19
+ end
20
+
21
+ private
22
+
23
+ def render_paginated_results_without_headers
5
24
  render json: {
6
- current_page: current_page,
7
- per_page: (params[:page].present? || params[:per_page].present?) ? per_page : filtered_objects.total_count,
8
- total_entries: filtered_objects.total_count,
9
- total_pages: (params[:page].present? || params[:per_page].present?) ? filtered_objects.total_pages : 1,
10
- records: filtered_objects_for_json
11
- }
25
+ current_page: current_page,
26
+ per_page: paginated_request? ? per_page : filtered_objects.total_count,
27
+ total_entries: filtered_objects.total_count,
28
+ total_pages: paginated_request? ? filtered_objects.total_pages : 1,
29
+ records: filtered_objects_for_json
30
+ }
31
+ end
32
+
33
+ def render_paginated_results_with_headers
34
+ render json: filtered_objects_for_json
35
+ end
36
+
37
+ def render_filtered_objects_as_json
38
+ if paginate_with_headers?
39
+ render_paginated_results_with_headers
40
+ else
41
+ render_paginated_results_without_headers
42
+ end
43
+ end
44
+
45
+ def add_pagination_headers
46
+ logger.debug { format 'Adding pagination headers for filtered_objects collection of size %d', filtered_objects.total_count }
47
+ response.headers['x-total'] = filtered_objects.total_count
48
+ response.headers['x-per-page'] = per_page
49
+ response.headers['x-page'] = current_page
50
+ end
51
+
52
+ def paginated_request?
53
+ params[:page].present? || params[:per_page].present?
12
54
  end
13
55
  end
14
56
  end
15
57
  end
16
-
@@ -6,4 +6,4 @@ module ElocalApiSupport
6
6
  end
7
7
  end
8
8
  end
9
- end
9
+ end
@@ -6,7 +6,7 @@ module ElocalApiSupport
6
6
  if lookup_object.update_attributes(params[associated_model_name])
7
7
  render json: lookup_object
8
8
  else
9
- render json: {errors: lookup_object.errors}, status: 422
9
+ render json: { errors: lookup_object.errors }, status: 422
10
10
  end
11
11
  end
12
12
  end
@@ -24,13 +24,20 @@ module ElocalApiSupport::Authorization
24
24
  end
25
25
 
26
26
  def authorize!
27
- unless authorized?
28
- Rails.logger.warn("Somebody else tried to access our internal API! Value: #{authorize_request_token} Params: #{params}, Headers: #{request.headers.map{ |k, _v| k }}")
29
- render json: error_response_hash, status: 401
30
- end
27
+ return if authorized?
28
+
29
+ Rails.logger.warn(
30
+ format(
31
+ 'Somebody else tried to access our internal API! Value: %s Params: %s, Headers: %s',
32
+ authorize_request_token,
33
+ params,
34
+ request.headers.map { |k, _v| k }
35
+ )
36
+ )
37
+ render json: error_response_hash, status: 401
31
38
  end
32
39
 
33
40
  def authorize_request_token
34
- [params[:request_token], request.headers["HTTP_X_REQUEST_TOKEN"]].detect(&:present?)
41
+ [params[:request_token], request.headers['HTTP_X_REQUEST_TOKEN']].detect(&:present?)
35
42
  end
36
43
  end
@@ -8,9 +8,9 @@ module ElocalApiSupport::EnableCors
8
8
  module ClassMethods
9
9
  attr_accessor :cors_allow_origin, :cors_allow_methods, :cors_allow_headers
10
10
  def cors_allow_all
11
- self.cors_allow_origin = "*"
12
- self.cors_allow_methods = %w{GET POST PUT DELETE}.join(",")
13
- self.cors_allow_headers = %w{Origin Accept Content-Type X-Requested-With X-XSRF-Token}.join(",")
11
+ self.cors_allow_origin = '*'
12
+ self.cors_allow_methods = %w(GET POST PUT DELETE).join(',')
13
+ self.cors_allow_headers = %w(Origin Accept Content-Type X-Requested-With X-XSRF-Token).join(',')
14
14
  end
15
15
  end
16
16
 
@@ -18,6 +18,6 @@ module ElocalApiSupport::EnableCors
18
18
  response.headers['Access-Control-Allow-Origin'] = self.class.cors_allow_origin
19
19
  response.headers['Access-Control-Allow-Methods'] = self.class.cors_allow_methods
20
20
  response.headers['Access-Control-Allow-Headers'] = self.class.cors_allow_headers
21
- head(:ok) if request.request_method == "OPTIONS"
21
+ head(:ok) if request.request_method == 'OPTIONS'
22
22
  end
23
23
  end
@@ -4,6 +4,7 @@ module ElocalApiSupport::ModelFromParams
4
4
  # - params
5
5
  # - associated_model_name
6
6
  #
7
+
7
8
  protected
8
9
 
9
10
  def lookup_object
@@ -30,7 +31,7 @@ module ElocalApiSupport::ModelFromParams
30
31
  elsif associated_model.respond_to?(:"with_#{param_name}", true)
31
32
  rel = rel.send(:"with_#{param_name}", params[param_name])
32
33
  else
33
- rel = rel.where({param_name.to_sym => params[param_name]})
34
+ rel = rel.where(param_name.to_sym => params[param_name])
34
35
  end
35
36
  end
36
37
  end
@@ -80,15 +81,12 @@ module ElocalApiSupport::ModelFromParams
80
81
  end
81
82
 
82
83
  def filter_sort_col
83
- if params[:sort] && params[:sort][:key] && allowed_sort_columns.include?(params[:sort][:key])
84
- params[:sort][:key]
85
- else
86
- nil
87
- end
84
+ params[:sort][:key] \
85
+ if params[:sort] && params[:sort][:key] && allowed_sort_columns.include?(params[:sort][:key])
88
86
  end
89
87
 
90
88
  def filter_sort_direction
91
- if params[:sort] && params[:sort][:direction] && ['asc','desc'].include?(params[:sort][:direction])
89
+ if params[:sort] && params[:sort][:direction] && %w(asc desc).include?(params[:sort][:direction])
92
90
  params[:sort][:direction]
93
91
  else
94
92
  ''
@@ -1,3 +1,3 @@
1
1
  module ElocalApiSupport
2
- VERSION = "0.1.2"
2
+ VERSION = '0.1.3'
3
3
  end
@@ -65,4 +65,4 @@ describe AuthController, type: :controller do
65
65
  expect(response).to have_http_status(200)
66
66
  end
67
67
  end
68
- end
68
+ end
@@ -3,12 +3,15 @@ require 'action_controller'
3
3
  require 'action_dispatch'
4
4
 
5
5
  module Rails
6
-
7
6
  class App
8
- def env_config; {} end
7
+ def env_config
8
+ {}
9
+ end
10
+
9
11
  def config
10
12
  OpenStruct.new
11
13
  end
14
+
12
15
  def routes
13
16
  return @routes if defined?(@routes)
14
17
  @routes = ActionDispatch::Routing::RouteSet.new
@@ -17,16 +20,17 @@ module Rails
17
20
  end
18
21
  @routes
19
22
  end
23
+
20
24
  def logger
21
25
  @logger ||= begin
22
- Dir.mkdir('log') unless Dir.exists?('log')
26
+ Dir.mkdir('log') unless Dir.exist?('log')
23
27
  Logger.new('log/test.log')
24
28
  end
25
29
  end
26
30
  end
27
31
 
28
32
  def self.logger
29
- self.application.logger
33
+ application.logger
30
34
  end
31
35
 
32
36
  def self.application
@@ -5,4 +5,4 @@ class FakesController < ActionController::Base
5
5
  def index
6
6
  render nothing: true
7
7
  end
8
- end
8
+ end
data/spec/spec_helper.rb CHANGED
@@ -23,65 +23,63 @@ require 'rspec/rails'
23
23
 
24
24
  require 'elocal_api_support'
25
25
 
26
- RSpec.configure do |config|
27
- # The settings below are suggested to provide a good initial experience
28
- # with RSpec, but feel free to customize to your heart's content.
29
- =begin
30
- # These two settings work together to allow you to limit a spec run
31
- # to individual examples or groups you care about by tagging them with
32
- # `:focus` metadata. When nothing is tagged with `:focus`, all examples
33
- # get run.
34
- config.filter_run :focus
35
- config.run_all_when_everything_filtered = true
36
-
37
- # Many RSpec users commonly either run the entire suite or an individual
38
- # file, and it's useful to allow more verbose output when running an
39
- # individual spec file.
40
- if config.files_to_run.one?
41
- # Use the documentation formatter for detailed output,
42
- # unless a formatter has already been configured
43
- # (e.g. via a command-line flag).
44
- config.default_formatter = 'doc'
45
- end
46
-
47
- # Print the 10 slowest examples and example groups at the
48
- # end of the spec run, to help surface which specs are running
49
- # particularly slow.
50
- config.profile_examples = 10
51
-
52
- # Run specs in random order to surface order dependencies. If you find an
53
- # order dependency and want to debug it, you can fix the order by providing
54
- # the seed, which is printed after each run.
55
- # --seed 1234
56
- config.order = :random
57
-
58
- # Seed global randomization in this process using the `--seed` CLI option.
59
- # Setting this allows you to use `--seed` to deterministically reproduce
60
- # test failures related to randomization by passing the same `--seed` value
61
- # as the one that triggered the failure.
62
- Kernel.srand config.seed
63
-
64
- # rspec-expectations config goes here. You can use an alternate
65
- # assertion/expectation library such as wrong or the stdlib/minitest
66
- # assertions if you prefer.
67
- config.expect_with :rspec do |expectations|
68
- # Enable only the newer, non-monkey-patching expect syntax.
69
- # For more details, see:
70
- # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
71
- expectations.syntax = :expect
72
- end
73
-
74
- # rspec-mocks config goes here. You can use an alternate test double
75
- # library (such as bogus or mocha) by changing the `mock_with` option here.
76
- config.mock_with :rspec do |mocks|
77
- # Enable only the newer, non-monkey-patching expect syntax.
78
- # For more details, see:
79
- # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
80
- mocks.syntax = :expect
81
-
82
- # Prevents you from mocking or stubbing a method that does not exist on
83
- # a real object. This is generally recommended.
84
- mocks.verify_partial_doubles = true
85
- end
86
- =end
26
+ RSpec.configure do |_config|
27
+ # The settings below are suggested to provide a good initial experience
28
+ # with RSpec, but feel free to customize to your heart's content.
29
+ # # These two settings work together to allow you to limit a spec run
30
+ # # to individual examples or groups you care about by tagging them with
31
+ # # `:focus` metadata. When nothing is tagged with `:focus`, all examples
32
+ # # get run.
33
+ # config.filter_run :focus
34
+ # config.run_all_when_everything_filtered = true
35
+ #
36
+ # # Many RSpec users commonly either run the entire suite or an individual
37
+ # # file, and it's useful to allow more verbose output when running an
38
+ # # individual spec file.
39
+ # if config.files_to_run.one?
40
+ # # Use the documentation formatter for detailed output,
41
+ # # unless a formatter has already been configured
42
+ # # (e.g. via a command-line flag).
43
+ # config.default_formatter = 'doc'
44
+ # end
45
+ #
46
+ # # Print the 10 slowest examples and example groups at the
47
+ # # end of the spec run, to help surface which specs are running
48
+ # # particularly slow.
49
+ # config.profile_examples = 10
50
+ #
51
+ # # Run specs in random order to surface order dependencies. If you find an
52
+ # # order dependency and want to debug it, you can fix the order by providing
53
+ # # the seed, which is printed after each run.
54
+ # # --seed 1234
55
+ # config.order = :random
56
+ #
57
+ # # Seed global randomization in this process using the `--seed` CLI option.
58
+ # # Setting this allows you to use `--seed` to deterministically reproduce
59
+ # # test failures related to randomization by passing the same `--seed` value
60
+ # # as the one that triggered the failure.
61
+ # Kernel.srand config.seed
62
+ #
63
+ # # rspec-expectations config goes here. You can use an alternate
64
+ # # assertion/expectation library such as wrong or the stdlib/minitest
65
+ # # assertions if you prefer.
66
+ # config.expect_with :rspec do |expectations|
67
+ # # Enable only the newer, non-monkey-patching expect syntax.
68
+ # # For more details, see:
69
+ # # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
70
+ # expectations.syntax = :expect
71
+ # end
72
+ #
73
+ # # rspec-mocks config goes here. You can use an alternate test double
74
+ # # library (such as bogus or mocha) by changing the `mock_with` option here.
75
+ # config.mock_with :rspec do |mocks|
76
+ # # Enable only the newer, non-monkey-patching expect syntax.
77
+ # # For more details, see:
78
+ # # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
79
+ # mocks.syntax = :expect
80
+ #
81
+ # # Prevents you from mocking or stubbing a method that does not exist on
82
+ # # a real object. This is generally recommended.
83
+ # mocks.verify_partial_doubles = true
84
+ # end
87
85
  end
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: elocal_api_support
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.2
4
+ version: 0.1.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Rob Di Marco
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2015-06-19 00:00:00.000000000 Z
11
+ date: 2015-06-25 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: activesupport
@@ -131,6 +131,7 @@ extra_rdoc_files: []
131
131
  files:
132
132
  - ".gitignore"
133
133
  - ".rspec"
134
+ - ".rubocop.yml"
134
135
  - Gemfile
135
136
  - LICENSE.txt
136
137
  - README.md
@@ -172,7 +173,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
172
173
  version: '0'
173
174
  requirements: []
174
175
  rubyforge_project:
175
- rubygems_version: 2.4.3
176
+ rubygems_version: 2.4.6
176
177
  signing_key:
177
178
  specification_version: 4
178
179
  summary: Utilities for controllers when creating a JSON API
@@ -181,3 +182,4 @@ test_files:
181
182
  - spec/fixtures/application.rb
182
183
  - spec/fixtures/controllers.rb
183
184
  - spec/spec_helper.rb
185
+ has_rdoc: