Skip to content

Commit

Permalink
add versionable logic
Browse files Browse the repository at this point in the history
  • Loading branch information
danielfornarini committed Oct 8, 2023
1 parent bdd5af9 commit 187aa31
Show file tree
Hide file tree
Showing 20 changed files with 500 additions and 7 deletions.
9 changes: 9 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Editor configuration, see https://editorconfig.org
root = true

[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
18 changes: 18 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: Ruby

on: [push,pull_request]

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: 3.0.1
- name: Run the default task
run: |
gem install bundler -v 2.2.15
bundle install
bundle exec rake
11 changes: 11 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/

# rspec failure tracking
.rspec_status
3 changes: 3 additions & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
--format documentation
--color
--require spec_helper
13 changes: 13 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
AllCops:
TargetRubyVersion: 2.4

Style/StringLiterals:
Enabled: true
EnforcedStyle: double_quotes

Style/StringLiteralsInInterpolation:
Enabled: true
EnforcedStyle: double_quotes

Layout/LineLength:
Max: 120
12 changes: 12 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

source "https://rubygems.org"

# Specify your gem's dependencies in deep_versionable.gemspec
gemspec

gem "rake", "~> 13.0"

gem "rspec", "~> 3.0"

gem "rubocop", "~> 1.7"
12 changes: 6 additions & 6 deletions LICENSE → LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License
The MIT License (MIT)

Copyright (c) 2023 Mònade
Copyright (c) 2023 Mònade srl

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand All @@ -9,13 +9,13 @@ 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 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.
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
40 changes: 39 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,39 @@
# deep_versionable
# DeepVersionable

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/deep_versionable`. To experiment with that code, run `bin/console` for an interactive prompt.

TODO: Delete this and the text above, and describe your gem

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'deep_versionable'
```

And then execute:

$ bundle install

Or install it yourself as:

$ gem install deep_versionable

## Usage

TODO: Write usage instructions here

## Development

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.

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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/deep_versionable.

## License

The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
12 changes: 12 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# frozen_string_literal: true

require "bundler/gem_tasks"
require "rspec/core/rake_task"

RSpec::Core::RakeTask.new(:spec)

require "rubocop/rake_task"

RuboCop::RakeTask.new

task default: %i[spec rubocop]
15 changes: 15 additions & 0 deletions bin/console
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env ruby
# frozen_string_literal: true

require "bundler/setup"
require "deep_versionable"

# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.

# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start

require "irb"
IRB.start(__FILE__)
8 changes: 8 additions & 0 deletions bin/setup
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx

bundle install

# Do any other automated setup that you need to do here
37 changes: 37 additions & 0 deletions deep_versionable.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# frozen_string_literal: true

require_relative "lib/deep_versionable/version"

Gem::Specification.new do |spec|
spec.name = "deep_versionable"
spec.version = DeepVersionable::VERSION
spec.authors = ["Daniel Fornarini"]
spec.email = ["[email protected]"]

spec.summary = "TODO: Write a short summary, because RubyGems requires one."
spec.description = "TODO: Write a longer description or delete this line."
spec.homepage = "TODO: Put your gem's website or public repo URL here."
spec.license = "MIT"
spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0")

spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"

spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "TODO: Put your gem's public repo URL here."
spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here."

# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path(__dir__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]

# Uncomment to register a new dependency of your gem
# spec.add_dependency "example-gem", "~> 1.0"

# For more information and examples about making a new gem, checkout our
# guide at: https://bundler.io/guides/creating_gem.html
end
92 changes: 92 additions & 0 deletions lib/deep_versionable.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# frozen_string_literal: true

require 'active_support/concern'

module DeepVersionable
extend ActiveSupport::Concern

module Initializer
def as_deep_versionable
send :include, DeepVersionable
end
end

included do
class_attribute :_deep_versionable_relations
has_many :versions, as: :versionable, dependent: :destroy
end

module ClassMethods
def deep_versionable(include: {})
declare_versionable_class(self.name)
self._deep_versionable_relations = parse_include(include, self)
end

private

def declare_versionable_class(name)
return if Object.const_defined?("DeepVersionable::Version::#{name}")

dynamic_class = Class.new(OpenStruct) do
include ActiveModel::Serialization

def initialize(object = nil)
super(object)
end
end

Version.const_set(name, dynamic_class)

declare_versionable_serializer(name) if Rails.configuration.deep_versionable_declare_serializers
end

def declare_versionable_serializer(name)
return if Object.const_defined?("DeepVersionable::Version::#{name}Serializer")

serializer = "#{name}Serializer".safe_constantize
# TODO: Implement logger
# Rails.logger.debug("Serializer #{name}Serializer not found. Using ApplicationSerializer for Version::#{name}") unless serializer

dynamic_class = Class.new(serializer || ApplicationSerializer) do
type name.underscore.pluralize
end

Version.const_set("#{name}Serializer", dynamic_class)
end

def parse_include(include, klass)
parsed_include = { include: [] }

include.each do |i|
if i.is_a?(Hash)
i.each do |k, v|
declare_versionable_class(load_class(klass, k).name)
parsed_include[:include] << { k => parse_include(v, load_class(klass, k)) }
end
else
declare_versionable_class(load_class(klass, i).name)
parsed_include[:include] << i
end
end

parsed_include
end

def load_class(klass, key)
association = klass.reflect_on_all_associations.detect { |e| e.name == key.to_sym }
class_name = association.options[:class_name] ? association.options[:class_name].to_s : key.to_s.classify

class_name.constantize
end
end

def versionize
object = to_json(self.class._deep_versionable_relations)

versions.create!(version: versions.count + 1, object: object)
end
end

# rubocop:disable Lint/SendWithMixinArgument
ActiveRecord::Base.send(:extend, DeepVersionable::Initializer)
# rubocop:enable Lint/SendWithMixinArgument
48 changes: 48 additions & 0 deletions lib/deep_versionable/models/version.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# frozen_string_literal: true

module DeepVersionable
class Version < ApplicationRecord
belongs_to :versionable, polymorphic: true

validates :version, :object, presence: true
validates :version, uniqueness: { scope: %i[versionable_id versionable_type] }

def reify
rebuild_model(versionable_type, JSON.parse(object))
end

private

def rebuild_model(klass, object)
object.each do |k, v|
next unless association_exists?(klass, k)

case v
when Hash
object[k] = rebuild_model(load_class(klass, k), v)
when Array
object[k] = v.map do |i|
if i.is_a?(Hash)
rebuild_model(load_class(klass, k), i)
else
i
end
end
end
end

instance = Version.const_get(klass).new(object)
instance.freeze
instance
end

def load_class(klass, key)
association = klass.constantize.reflect_on_all_associations.detect { |e| e.name == key.to_sym }
association.options[:class_name] ? association.options[:class_name].to_s : key.to_s.classify
end

def association_exists?(klass, key)
klass.constantize.reflect_on_all_associations.detect { |e| e.name == key.to_sym }.present?
end
end
end
5 changes: 5 additions & 0 deletions lib/deep_versionable/version.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# frozen_string_literal: true

module DeepVersionable
VERSION = "0.1.0"
end
Loading

0 comments on commit 187aa31

Please sign in to comment.