Skip to content

[WIP] Initial Implementation #1

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
--require spec_helper --color --format documentation
75 changes: 75 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
AllCops:
Exclude:
- config/initializers/forbidden_yaml.rb
- !ruby/regexp /(vendor|bundle|bin|db|tmp)\/.*/
DisplayCopNames: true
DisplayStyleGuide: true
TargetRubyVersion: 2.3

Lint/AssignmentInCondition:
Enabled: false

Lint/NestedMethodDefinition:
Enabled: false

Style/FrozenStringLiteralComment:
EnforcedStyle: always

Style/StringLiterals:
EnforcedStyle: single_quotes

Metrics/AbcSize:
Max: 35 # TODO: Lower to 15

Metrics/ClassLength:
Max: 261 # TODO: Lower to 100
Exclude:
- test/**/*.rb

Metrics/CyclomaticComplexity:
Max: 7 # TODO: Lower to 6

Metrics/LineLength:
Max: 110 # TODO: Lower to 80

Metrics/MethodLength:
Max: 25

Metrics/BlockLength:
Exclude:
- spec/**/*

Metrics/PerceivedComplexity:
Max: 9 # TODO: Lower to 7

Style/AlignParameters:
EnforcedStyle: with_fixed_indentation

Style/ClassAndModuleChildren:
EnforcedStyle: nested

Style/Documentation:
Enabled: false

Style/DoubleNegation:
Enabled: false

Style/MissingElse:
Enabled: false # TODO: maybe enable this?
EnforcedStyle: case

Style/EmptyElse:
EnforcedStyle: empty

Style/MultilineOperationIndentation:
EnforcedStyle: indented

Style/BlockDelimiters:
Enabled: true
EnforcedStyle: line_count_based

Style/PredicateName:
Enabled: false # TODO: enable with correct prefixes

Style/ClassVars:
Enabled: false
4 changes: 4 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
source 'https://rubygems.org'

# Add a Gemfile.local to locally bundle gems outside of version control
local_gemfile = File.join(File.expand_path('..', __FILE__), 'Gemfile.local')
eval_gemfile local_gemfile if File.readable?(local_gemfile)

gemspec
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2016 Lucas Hosseini

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
13 changes: 9 additions & 4 deletions jsonapi-rails.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,17 @@ Gem::Specification.new do |spec|
spec.files = Dir['README.md', 'lib/**/*']
spec.require_path = 'lib'

spec.add_dependency 'jsonapi-renderer', '0.1.1.beta2'
spec.add_dependency 'jsonapi-parser', '0.1.1.beta3'
spec.add_dependency 'jsonapi-serializable', '0.1.1.beta2'
spec.add_dependency 'jsonapi-deserializable', '0.1.1.beta3'
spec.add_dependency 'jsonapi-renderer', '~> 0.1.1.beta2'
spec.add_dependency 'jsonapi-parser', '~> 0.1.1.beta3'
spec.add_dependency 'jsonapi-serializable', '~> 0.1.1.beta2'
spec.add_dependency 'jsonapi-deserializable', '~> 0.1.1.beta3'

# because this gem is intended for rails use, active_support will
# already be included
spec.add_dependency 'activesupport', '> 4.0'

spec.add_development_dependency 'activerecord', '>=5'
spec.add_development_dependency 'rails', '>=5'
spec.add_development_dependency 'sqlite3', '>= 1.3.12'
spec.add_development_dependency 'rake', '>=0.9'
spec.add_development_dependency 'rspec', '~>3.4'
Expand Down
3 changes: 3 additions & 0 deletions lib/jsonapi.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module JSONAPI
require_relative 'jsonapi/rails'
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why require_relative and not require?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was using require_relative everywhere else

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That does not really address the question :D

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't want to require the whole path jsonapi/etc for every require.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah but here this is the whole path. Plus it's not like we require shittons of stuff so I'd be in favor of using require everywhere.

end
17 changes: 17 additions & 0 deletions lib/jsonapi/deserializable.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
module JSONAPI
module Deserializable
require_relative 'deserializable/active_record'

module_function

def to_active_record_hash(hash, options: {}, klass: nil)

# TODO: maybe JSONAPI::Document::Deserialization.to_active_record_hash(...)?
JSONAPI::Deserializable::ActiveRecord.new(
hash,
options: options,
klass: klass
).to_hash
end
end
end
76 changes: 76 additions & 0 deletions lib/jsonapi/deserializable/active_record.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# frozen_string_literal: true
require 'jsonapi/deserializable'

module JSONAPI
module Deserializable
# This does not validate a JSON API document, so errors may happen.
# To truely ensure valid documents are used, it would be recommended to
# use either of
# - JSONAPI::Parser - for general parsing and validating
# - JSONAPI::Validations - for defining validation logic.
#
# for 'filtereing' of fields, use ActionController::Parameters
#
# TODO:
# - add option for type-seperator string
# - add options for specifying polymorphic relationships
# - this will try to be inferred based on the klass's associations
# - cache deserializable_for_class
# - allow custom deserializable_classes?
# - then this gem would just be a very light weight wrapper around
# jsonapi/deserializable
class ActiveRecord
require_relative 'active_record/builder'

class << self
def deserializable_cache
@deserializable_cache ||= {}
end

# Creates a DeserializableResource class based off all the
# attributes and relationships
#
# @example
# JSONAPI::Deserializable::ActiveRecord[Post].new(params)
def [](klass)
deserializable_cache[klass.name] ||= deserializable_for(klass)
end

def deserializable_for(klass)
JSONAPI::Deserializable::ActiveRecord::Builder.for_class(klass)
end

def deserializable_class(type, klass)
klass || type_to_model(type)
end

def type_to_model(type)
type.classify.safe_constantize
end
end

# if this class is instatiated directly, i.e.: without a spceified
# class via
# JSONAPI::Deserializable::ActiveRecord[ExampleClass]
# then when to_hash is called, the class will be derived, and
# a class will be used for deserialization as if the
# user specified the deserialization target class.
def initialize(hash, options: {}, klass: nil)
@hash = hash
@options = options
@klass = klass
end

def to_hash
type = @hash['data']['type']
klass = self.class.deserializable_class(type, @klass)

if klass.nil?
raise "FATAL: class not found for type of `#{type}` or specified @klass `#{@klass&.name}`"
end

self.class[klass].call(@hash).with_indifferent_access
end
end
end
end
84 changes: 84 additions & 0 deletions lib/jsonapi/deserializable/active_record/builder.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
require 'jsonapi/deserializable/resource'

module JSONAPI
module Deserializable
class ActiveRecord
module Builder
require 'active_support/core_ext/string'

module_function

def for_class(klass)
builder = self
Class.new(JSONAPI::Deserializable::Resource) do
# All Attributes
builder.define_attributes(self, klass)

# All Associations
builder.define_associations(self, klass)
end
end

def define_attributes(deserializable, klass)
attributes = attributes_for_class(klass)

deserializable.class_eval do
attributes.each do |attribute_name|
attribute attribute_name
end
end
end

def define_associations(deserializable, klass)
associations = associations_for_class(klass)

deserializable.class_eval do
associations.each do |name, reflection|
if reflection.collection?
has_many name do |rel|
field "#{name}_ids" => rel['data'].map { |ri| ri['id'] }
# field "#{name}_type" => rel['data'] && rel['data']['type']
end
else
has_one name do |rel|
field "#{name}_id" => rel['data'] && rel['data']['id']

if reflection.polymorphic?
field "#{name}_type" => rel['data'] && rel['data']['type'].classify
end
end
end
end
end
end

def self.attributes_for_class(klass)
klass.columns.map(&:name)
end

# @return [Hash]
# example:
# {
# 'author' => #<ActiveRecord::Reflection::BelongsToReflection ...>,
# 'comments' => #<ActiveRecord::Reflection::HasManyReflection ...>
# }
#
# for a reflection, the import parts for deserialization may be as follows:
# - Reflection (BelongsTo / HasMany)
# - name - symbol version of the association name (e.g.: :author)
# - collection? - if the reflection is a collection of records
# - class_name - AR Class of the association
# - foreign_type - name of the polymorphic type column
# - foreign_key - name of the foreign_key column
# - polymorphic? - true/false/nil
# - type - name of the type column (for STI)
#
# To see a full list of reflection methods:
# ap klass.reflections['reflection_name'].methods - Object.methods
def self.associations_for_class(klass)
klass.reflections
end
end # Builder
end # DeserializableResource
end # Rails
end # JSONAPI
Loading