hal_api-rails 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: cea939b833fbbe9155587026dfc9fc5f6bcadf8a
4
+ data.tar.gz: a8587cf6a4d13da538874e8fa1f795be9d2c99df
5
+ SHA512:
6
+ metadata.gz: 25ac0d46c54b7a09e012580dead423d3a336894fe8af44d16b95a534e99f53363ed3230c8243c651713fbf8b551895780f45818f3b438934a1906827b07aa700
7
+ data.tar.gz: f074268d356d73b338d8fe1d8a98c139c6b85a545e5ec32f41baf788f633d0851808f732c16fab960eb4245d026272097f74276bd2d94e252f3a96dcf25f006e
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ .DS_Store
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.0.0
4
+ before_install: gem install bundler -v 1.10.6
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ 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. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in hal_api-rails.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2015 Chris Rhoden
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # HalApi::Rails
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/hal_api/rails`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'hal_api-rails'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install hal_api-rails
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/hal_api-rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
36
+
37
+
38
+ ## License
39
+
40
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
41
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task :default => :test
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "hal_api/rails"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,33 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'hal_api/rails/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "hal_api-rails"
8
+ spec.version = HalApi::Rails::VERSION
9
+ spec.authors = ["Chris Rhoden", "Andrew Kuklewicz"]
10
+ spec.email = ["carhoden@gmail.com", "andrew@beginsinwonder.com"]
11
+
12
+ spec.summary = %q{JSON HAL APIs on Rails in the style of PRX}
13
+ spec.description = %q{JSON HAL APIs on Rails in the style of PRX v4. Uses ROAR}
14
+ spec.homepage = "https://www.github.com/PRX/"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
18
+ spec.bindir = "exe"
19
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_dependency "activemodel", ">= 3.0.0"
23
+ spec.add_dependency "actionpack", ">= 3.0.0"
24
+ spec.add_dependency "rack-test", "~> 0.6.2"
25
+ spec.add_dependency "activesupport", ">= 3.0.0"
26
+ spec.add_dependency "responders", "~> 2.0"
27
+ spec.add_dependency "roar-rails", "~> 1.0.1"
28
+ spec.add_dependency "multi_json"
29
+
30
+ spec.add_development_dependency "bundler", "~> 1.10"
31
+ spec.add_development_dependency "rake", "~> 10.0"
32
+ spec.add_development_dependency "minitest"
33
+ end
data/lib/hal_api.rb ADDED
@@ -0,0 +1,7 @@
1
+ module HalApi
2
+ require 'hal_api/paged_collection'
3
+ require 'hal_api/errors'
4
+ require 'hal_api/controller'
5
+ # require 'hal_api/representer'
6
+ require 'hal_api/represented_model'
7
+ end
@@ -0,0 +1,39 @@
1
+ require 'active_support/concern'
2
+ require 'responders'
3
+ require 'roar-rails'
4
+
5
+ module HalApi::Controller
6
+ extend ActiveSupport::Concern
7
+
8
+ require 'hal_api/controller/actions'
9
+ require 'hal_api/controller/cache'
10
+ require 'hal_api/controller/resources'
11
+ require 'hal_api/controller/exceptions'
12
+
13
+ include HalApi::Controller::Actions
14
+ include HalApi::Controller::Cache
15
+ include HalApi::Controller::Resources
16
+ include HalApi::Controller::Exceptions
17
+
18
+ included do
19
+ include Roar::Rails::ControllerAdditions
20
+
21
+ before_action :set_accepts
22
+ respond_to :hal, :json
23
+
24
+ hal_rescue_standard_errors
25
+ end
26
+
27
+ module ClassMethods
28
+ include HalApi::Controller::Actions::ClassMethods
29
+ include HalApi::Controller::Cache::ClassMethods
30
+ include HalApi::Controller::Resources::ClassMethods
31
+ include HalApi::Controller::Exceptions::ClassMethods
32
+ end
33
+
34
+ private
35
+
36
+ def set_accepts
37
+ request.format = :json if request.format == Mime::HTML
38
+ end
39
+ end
@@ -0,0 +1,116 @@
1
+ module HalApi::Controller::Actions
2
+ def index
3
+ respond_with index_collection, index_options
4
+ end
5
+
6
+ def show
7
+ respond_with root_resource(show_resource), show_options
8
+ end
9
+
10
+ def create
11
+ create_resource.tap do |res|
12
+ consume_with_content_type! res
13
+ hal_authorize res
14
+ res.save!
15
+ respond_with root_resource(res), show_options
16
+ end
17
+ end
18
+
19
+ def update
20
+ update_resource.tap do |res|
21
+ consume_with_content_type! res
22
+ hal_authorize res
23
+ res.save!
24
+ respond_with root_resource(res), show_options
25
+ end
26
+ end
27
+
28
+ def destroy
29
+ destroy_resource.tap do |res|
30
+ hal_authorize res
31
+ res.destroy
32
+ head :no_content
33
+ end
34
+ end
35
+
36
+ private
37
+
38
+ def destroy_redirect
39
+ { action: 'index' }
40
+ end
41
+
42
+ def index_options
43
+ valid_params_for_action(:index).tap do |options|
44
+ options[:_keys] = options.keys
45
+ end
46
+ end
47
+
48
+ def show_options
49
+ valid_params_for_action(:show).tap do |options|
50
+ options[:_keys] = options.keys
51
+ if self.class.resource_representer
52
+ options[:represent_with] = self.class.resource_representer
53
+ end
54
+ end
55
+ end
56
+
57
+ def valid_params_for_action(action)
58
+ (params.slice(*self.class.valid_params_list(action)) || {}).tap do |p|
59
+ p[:zoom] = zoom_param if zoom_param
60
+ end
61
+ end
62
+
63
+ def zoom_param
64
+ @zoom_param ||= begin
65
+ if (zp = params[:zoom]) && zp.present?
66
+ zp.split(',').map(&:strip).compact.sort
67
+ end
68
+ end
69
+ end
70
+
71
+ def root_resource(resource)
72
+ resource.tap { |res| res.is_root_resource = true }
73
+ end
74
+
75
+ # TODO: Remove this method when we upgrade roar-rails
76
+ # Background: https://github.com/apotonick/roar-rails/blob/a109b40/lib/roar/rails/controller_additions.rb#L27
77
+ def consume_with_content_type!(model, options = {})
78
+ type = request.content_type
79
+ format = Mime::Type.lookup(type).try(:symbol)
80
+
81
+ if format.blank?
82
+ raise HalApi::Errors::UnsupportedMediaType.new(type)
83
+ end
84
+
85
+ parse_method = compute_parsing_method(format)
86
+ representer = prepare_model_for(format, model, options)
87
+
88
+ representer.send(parse_method, incoming_string, options)
89
+ model
90
+ end
91
+
92
+ def hal_authorize(resource)
93
+ if respond_to?(:authorize)
94
+ authorize(resource)
95
+ else
96
+ define_singleton_method(:authorize, Proc.new(resource) do
97
+ true
98
+ end)
99
+ singleton_class.send(:alias_method, :hal_authorize, :authorize)
100
+ end
101
+ end
102
+
103
+
104
+ module ClassMethods
105
+ attr_accessor :valid_params
106
+
107
+ def allow_params(action, *params)
108
+ self.valid_params ||= {}
109
+ valid_params[action.to_sym] = Array(params).flatten
110
+ end
111
+
112
+ def valid_params_list(action)
113
+ (valid_params || {})[action.to_sym]
114
+ end
115
+ end
116
+ end
@@ -0,0 +1,34 @@
1
+ module HalApi::Controller::Cache
2
+ private
3
+
4
+ def index_cache_path
5
+ HalApi::PagedCollection.new(
6
+ filtered(paged(sorted(scoped(resources_base)))),
7
+ request,
8
+ item_class: self.class.resource_class,
9
+ item_decorator: self.class.resource_representer
10
+ ).cache_key
11
+ end
12
+
13
+ def show_cache_path
14
+ show_resource.updated_at.utc.to_i
15
+ end
16
+
17
+ module ClassMethods
18
+ def cache_api_action(action, options = {})
19
+ options = cache_options.merge(options || {})
20
+ cache_path_method = options.delete(:cache_path_method)
21
+ cache_path_method ||= "#{action}_cache_path"
22
+ unless options[:cache_path]
23
+ options[:cache_path] = lambda do |c|
24
+ c.send(:valid_params_for_action, action).merge _c: send(cache_path_method)
25
+ end
26
+ end
27
+ caches_action(action, options)
28
+ end
29
+
30
+ def cache_options
31
+ { compress: true, expires_in: 1.hour, race_condition_ttl: 30 }
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,43 @@
1
+ require 'action_dispatch/http/request'
2
+ require 'action_dispatch/middleware/exception_wrapper'
3
+
4
+ # Since we are taking over exception handling, make sure we log exceptions
5
+ # https://github.com/rails/rails/blob/4-2-stable/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb
6
+ module HalApi::Controller::Exceptions
7
+ def respond_with_error(exception)
8
+ wrapper = ::ActionDispatch::ExceptionWrapper.new(env, exception)
9
+ log_error(env, wrapper)
10
+
11
+ error = exception.is_a?(HalApi::Errors::ApiError) ? exception : HalApi::Errors::ApiError.new
12
+ respond_with(
13
+ error,
14
+ status: error.status,
15
+ represent_with: HalApi::Errors::Representer
16
+ )
17
+ end
18
+
19
+ def log_error(env, wrapper)
20
+ logger = env['action_dispatch.logger'] || ActiveSupport::Logger.new($stderr)
21
+ return unless logger
22
+
23
+ exception = wrapper.exception
24
+
25
+ trace = wrapper.application_trace
26
+ trace = wrapper.framework_trace if trace.empty?
27
+
28
+ ActiveSupport::Deprecation.silence do
29
+ message = "\n#{exception.class} (#{exception.message}):\n"
30
+ message << exception.annoted_source_code.to_s if exception.respond_to?(:annoted_source_code)
31
+ message << " " << trace.join("\n ")
32
+ logger.fatal("#{message}\n\n")
33
+ end
34
+ end
35
+
36
+ module ClassMethods
37
+ def hal_rescue_standard_errors
38
+ rescue_from StandardError do |error|
39
+ respond_with_error(error)
40
+ end
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,135 @@
1
+ module HalApi::Controller::Resources
2
+ private
3
+
4
+ # action specific resources
5
+
6
+ def index_collection
7
+ HalApi::PagedCollection.new(
8
+ resources,
9
+ request,
10
+ item_class: self.class.resource_class,
11
+ item_decorator: self.class.resource_representer
12
+ )
13
+ end
14
+
15
+ def show_resource
16
+ resource
17
+ end
18
+
19
+ def update_resource
20
+ resource
21
+ end
22
+
23
+ def create_resource
24
+ resource
25
+ end
26
+
27
+ def destroy_resource
28
+ resource
29
+ end
30
+
31
+ def resource
32
+ resource = instance_variable_get("@#{resource_name}")
33
+ return resource if resource
34
+
35
+ resource = if params[:id]
36
+ find_base.send(self.class.find_method, params[:id])
37
+ elsif request.post?
38
+ filtered(resources_base).build
39
+ end
40
+ raise HalApi::Errors::NotFound.new if resource.nil?
41
+ self.resource = resource
42
+ end
43
+
44
+ def resource=(res)
45
+ instance_variable_set("@#{resource_name}", res)
46
+ end
47
+
48
+ def resource_name
49
+ self.class.resource_class.name.underscore
50
+ end
51
+
52
+ # Plural resources
53
+
54
+ def resources
55
+ instance_variable_get("@#{resources_name}") ||
56
+ self.resources = decorate_query(resources_base)
57
+ end
58
+
59
+ def resources=(res)
60
+ instance_variable_set("@#{resources_name}", res)
61
+ end
62
+
63
+ def resources_name
64
+ resource_name.pluralize
65
+ end
66
+
67
+ def resources_base
68
+ self.class.resource_class.where(nil)
69
+ end
70
+
71
+ def find_base
72
+ filtered(scoped(included(resources_base)))
73
+ end
74
+
75
+ # Decorations
76
+
77
+ def decorate_query(res)
78
+ filtered(paged(sorted(scoped(res))))
79
+ end
80
+
81
+ def filtered(arel)
82
+ keys = self.class.resources_params || []
83
+ where_hash = params.slice(*keys)
84
+ if where_hash.key?('story_id')
85
+ where_hash['piece_id'] = where_hash.delete('story_id')
86
+ end
87
+ where_hash = where_hash.permit(where_hash.keys)
88
+ arel = arel.where(where_hash) unless where_hash.blank?
89
+ arel
90
+ end
91
+
92
+ def included(res)
93
+ res
94
+ end
95
+
96
+ def paged(arel)
97
+ arel.page(params[:page]).per(params[:per])
98
+ end
99
+
100
+ def scoped(res)
101
+ res
102
+ end
103
+
104
+ def sorted(arel)
105
+ arel.order(id: :desc)
106
+ end
107
+
108
+ module ClassMethods
109
+ attr_accessor :resource_class, :resources_params, :resource_representer, :find_method
110
+
111
+ def filter_resources_by(*rparams)
112
+ self.resources_params = rparams
113
+ end
114
+
115
+ def represent_with(representer_class)
116
+ self.resource_representer = representer_class
117
+ end
118
+
119
+ def find_method(new_method=nil)
120
+ if new_method.present?
121
+ @find_method = new_method
122
+ else
123
+ @find_method ||= :find
124
+ end
125
+ end
126
+
127
+ def resource_class
128
+ @resource_class ||= controller_name.classify.constantize.tap do |klass|
129
+ unless klass.included_modules.include?(HalApi::RepresentedModel)
130
+ klass.send(:include, HalApi::RepresentedModel)
131
+ end
132
+ end
133
+ end
134
+ end
135
+ end