grape_on_rails 1.0.1

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.
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.1
5
+ before_install: gem install bundler -v 1.15.4
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at topcbl@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,41 @@
1
+ source "https://rubygems.org"
2
+
3
+ git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
4
+
5
+ # Specify your gem's dependencies in grape_on_rails.gemspec
6
+ gemspec
7
+
8
+ gem 'rack', github: 'rack/rack'
9
+ gem 'arel', github: 'rails/arel'
10
+ gem 'rails', github: 'rails/rails'
11
+ git 'https://github.com/rails/rails.git' do
12
+ gem 'railties'
13
+ gem 'activesupport'
14
+ gem 'actionpack'
15
+ gem 'activerecord', group: :test
16
+ end
17
+
18
+ # https://github.com/bundler/bundler/blob/89a8778c19269561926cea172acdcda241d26d23/lib/bundler/dependency.rb#L30-L54
19
+ @windows_platforms = [:mswin, :mingw, :x64_mingw]
20
+
21
+ # Windows does not include zoneinfo files, so bundle the tzinfo-data gem
22
+ gem 'tzinfo-data', platforms: (@windows_platforms + [:jruby])
23
+
24
+ group :test do
25
+ gem 'pry', '>= 0.10'
26
+ gem 'byebug', '~> 8.2' if RUBY_VERSION < '2.2'
27
+ gem 'pry-byebug', platform: :ruby
28
+ end
29
+
30
+ group :development, :test do
31
+ gem "pry"
32
+ gem "pry-rails"
33
+ gem "pry-byebug"
34
+ gem "byebug", platforms: [:mri, :mingw, :x64_mingw]
35
+ gem "rspec"
36
+ gem "rspec-rails"
37
+ gem "rspec-its"
38
+ gem "rspec-collection_matchers"
39
+ gem "rubocop", "~> 0.49.0", require: false
40
+ gem "rubocop-checkstyle_formatter", require: false
41
+ end
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 topcbl
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.
@@ -0,0 +1,45 @@
1
+ # GrapeOnRails
2
+
3
+ * Want to get rid of boilerplate code
4
+ * Want to keep using Rails api-only mode without mess with Grape
5
+ * Have an easy life
6
+
7
+ Introduce gem GrapeOnRails - which brings Grape DSL to Rails-API and help writing APIs easier than ever
8
+
9
+ ## Installation
10
+
11
+ Add this line to your application's Gemfile:
12
+
13
+ ```ruby
14
+ gem 'grape_on_rails'
15
+ ```
16
+
17
+ And then execute:
18
+
19
+ $ bundle
20
+
21
+ Or install it yourself as:
22
+
23
+ $ gem install grape_on_rails
24
+
25
+ ## Usage
26
+
27
+ TODO:
28
+
29
+ ## Development
30
+
31
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
32
+
33
+ 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).
34
+
35
+ ## Contributing
36
+
37
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/grape_on_rails. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
38
+
39
+ ## License
40
+
41
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
42
+
43
+ ## Code of Conduct
44
+
45
+ Everyone interacting in the GrapeOnRails project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/grape_on_rails/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "grape_on_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(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,33 @@
1
+ # coding: utf-8
2
+
3
+ lib = File.expand_path("../lib", __FILE__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require "grape_on_rails/version"
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = "grape_on_rails"
9
+ spec.version = GrapeOnRails::VERSION
10
+ spec.authors = ["topcbl"]
11
+ spec.email = ["topcbl@gmail.com"]
12
+
13
+ spec.summary = %q(Bring Grape DSL to Rails-api. Make it easier for writing api.)
14
+ spec.description = %q(Bring Grape DSL to Rails-api. Make it easier for writing api.)
15
+ spec.homepage = "https://github.com/chau-bao-long/grape-on-rails"
16
+ spec.license = "MIT"
17
+
18
+ spec.files = `git ls-files -z`.split("\x0")
19
+ spec.bindir = "exe"
20
+ spec.executables = spec.files.grep(%r{^exe/}){|f| File.basename(f)}
21
+ spec.require_paths = ["lib"]
22
+
23
+ rails_versions = [">= 4.1", "< 6"]
24
+
25
+ spec.add_runtime_dependency "actionpack", rails_versions
26
+ spec.add_runtime_dependency "activerecord", rails_versions
27
+ spec.add_runtime_dependency "activesupport", rails_versions
28
+ spec.add_runtime_dependency "railties", rails_versions
29
+
30
+ spec.add_development_dependency "bundler", "~> 1.15"
31
+ spec.add_development_dependency "rake", "~> 10.0"
32
+ spec.add_development_dependency "rspec", "~> 3.0"
33
+ end
@@ -0,0 +1,78 @@
1
+ require "grape_on_rails/version"
2
+ require "active_support/dependencies/autoload"
3
+ require "active_support/core_ext/array/extract_options"
4
+ require 'active_support/core_ext/module/attribute_accessors'
5
+ require "active_support/concern"
6
+ require "grape_on_rails/sources/yaml_source"
7
+ require "grape_on_rails/structural_hash"
8
+ require "grape_on_rails/support"
9
+ require "grape_on_rails/types/boolean"
10
+
11
+ # rubocop:disable ModuleFunction, ClassVars
12
+ module GrapeOnRails
13
+ extend ActiveSupport::Autoload
14
+ extend self
15
+
16
+ autoload :API
17
+ autoload :APIError
18
+ autoload :Authenticator
19
+ autoload :Models
20
+ autoload :SecuredGenerator
21
+
22
+ mattr_accessor :config_file, :short_name
23
+
24
+ @@_ran_once = false
25
+ @@config_file = "grape_on_rails.yml"
26
+ @@short_name = "GoR"
27
+
28
+ def setup
29
+ return if @@_ran_once
30
+ @@_ran_once = true
31
+ block_given? ? yield(self) : hook_rails_layers
32
+ end
33
+
34
+ def load
35
+ config = load_file
36
+ Kernel.send(:remove_const, short_name) if Kernel.const_defined?(short_name)
37
+ Kernel.const_set short_name, config
38
+ Models.set_default_model_actors config
39
+ create_error_class config
40
+ end
41
+
42
+ alias :reload :load
43
+
44
+ private
45
+ def load_file
46
+ file = Rails.root.join("config", config_file)
47
+ source = Sources::YAMLSource.new(file.to_s).load
48
+ StructuralHash.new.from_hash source
49
+ end
50
+
51
+ def create_error_class config
52
+ config.errors.each do |error|
53
+ next if error.second.skip_create_error
54
+ error_name = error.first.to_s.classify
55
+ APIError.const_set error_name, Class.new(APIError::Base) unless APIError.const_defined?(error_name)
56
+ end
57
+ end
58
+
59
+ def hook_rails_layers
60
+ hook_controller GrapeOnRails::API, GrapeOnRails::Authenticator
61
+ hook_model GrapeOnRails::Models
62
+ end
63
+
64
+ def hook_controller *modules
65
+ modules.each do |mod|
66
+ ActionController::Metal.include mod unless ActionController::Metal < mod
67
+ end
68
+ end
69
+
70
+ def hook_model *modules
71
+ modules.each do |mod|
72
+ ActiveRecord::Base.extend mod unless ActiveRecord::Base.singleton_class < mod
73
+ end
74
+ end
75
+ end
76
+ # rubocop:enable ModuleFunction, ClassVars
77
+
78
+ require("grape_on_rails/integrations/railtie") if defined?(::Rails)
@@ -0,0 +1,36 @@
1
+ require "grape_on_rails/error_formatter"
2
+ require "grape_on_rails/validator"
3
+
4
+ module GrapeOnRails
5
+ module API
6
+ extend ActiveSupport::Concern
7
+
8
+ include ActiveSupport::Rescuable
9
+ include Validator
10
+ include ErrorFormatter
11
+ include Support
12
+
13
+ included do
14
+ rescue_from APIError::Base do |e|
15
+ render_error class_name(e), e.message, e.status
16
+ end
17
+
18
+ rescue_from ActiveRecord::UnknownAttributeError, ActiveRecord::StatementInvalid, JSON::ParserError do |e|
19
+ render_error :data_operation, e.message, :internal_server_error
20
+ end
21
+
22
+ rescue_from ActiveRecord::RecordNotFound do
23
+ render_error :record_not_found, gor_t("record_not_found"), :bad_request
24
+ end
25
+
26
+ rescue_from ActiveRecord::RecordInvalid do |e|
27
+ render_error :record_invalid, e.message, :bad_request
28
+ end
29
+
30
+ private
31
+ def r resources, extra_params = {}
32
+ render extra_params.merge json: resources
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,19 @@
1
+ module GrapeOnRails
2
+ module APIError
3
+ class Base < StandardError
4
+ include Support
5
+
6
+ attr_reader :status
7
+
8
+ def initialize message = nil, status = nil
9
+ super message || localize_message
10
+ @status = status || :bad_request
11
+ end
12
+
13
+ private
14
+ def localize_message
15
+ gor_translate class_name(self)
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,52 @@
1
+ module GrapeOnRails
2
+ module Attributes
3
+ TYPE = {BigDecimal: "to_d", DateTime: "to_datetime", Date: "to_date", Time: "to_time"}.freeze
4
+
5
+ def declared_attrs attrs
6
+ @declared_attrs ||= []
7
+ @declared_attrs |= attrs
8
+ end
9
+
10
+ def declared_params
11
+ params.permit @declared_attrs
12
+ end
13
+
14
+ def undeclare_params *params
15
+ @declared_attrs -= params
16
+ end
17
+
18
+ private
19
+ def verify method, attrs, value
20
+ attrs.each do |attr|
21
+ is_valid = send "verify_#{method}", attr, value
22
+ raise APIError::ValidationError, "#{attr} #{I18n.t "errors.messages.#{method}"}" unless is_valid
23
+ instance_variable_set "@#{attr}".to_sym, params[attr]
24
+ self.class.class_eval{attr_reader attr}
25
+ end
26
+ end
27
+
28
+ def verify_type attr, type, param = nil
29
+ return verify_type_in_array attr, type if type.is_a? Array
30
+ return true if type == File
31
+ param ||= params[attr]
32
+ param.class.include GrapeOnRails::Types::Boolean if type == GrapeOnRails::Types::Boolean
33
+ convert_method = TYPE[type.name.to_sym] || "to_#{type.name[0].downcase}"
34
+ params[attr] = param.public_send convert_method
35
+ true
36
+ rescue StandardError
37
+ false
38
+ end
39
+
40
+ def verify_type_in_array attr, type
41
+ params[attr].all?{|p| verify_type(attr, type.to_a.first, param: p)}
42
+ end
43
+
44
+ def verify_allow_blank attr, is_allow
45
+ params[attr].present? || is_allow
46
+ end
47
+
48
+ def verify_regexp attr, regex
49
+ params[attr] =~ regex
50
+ end
51
+ end
52
+ end