sdl 0.1.0

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,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: a6e61a1d5604a66b42b6fb6c1d9ef23cafe16f82
4
+ data.tar.gz: 9c0aed1be31e2fd105bdf4797aae965a2470c9cf
5
+ SHA512:
6
+ metadata.gz: c507bebf2605c7dd156219e5ec791660279daf1de15d05cdffcbe5ed2142888c62b657033d6c2b7015565a4824cf5d5282df8919f63169559e9d9d5965c7ddbc
7
+ data.tar.gz: 3f0982e9b1785c24a7a5f619bdaa7910f9559310a31008157a9043b2a4dce68172c21b01f4da11992e4022bbb3f711c9feac54ef4ad584cc8cf42bddc9e46375
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+
13
+ Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.5.3
7
+ before_install: gem install bundler -v 2.0.2
@@ -0,0 +1,6 @@
1
+ --output-dir=doc/api
2
+ --embed-mixins
3
+ --protected
4
+ --no-private
5
+ --markup-provider=redcarpet
6
+ --markup=markdown
@@ -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 raymondzane@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,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in sdl.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Ray Zane
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,80 @@
1
+ # SDL
2
+
3
+ SDL is generic schema definition language.
4
+
5
+ Alone, it doesn't do anything useful. However, you might find it to be helpful
6
+ for the purpose of code generation.
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem 'sdl'
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ $ bundle
19
+
20
+ Or install it yourself as:
21
+
22
+ $ gem install sdl
23
+
24
+ ## Examples
25
+
26
+ ### Define a schema
27
+
28
+ ```ruby
29
+ SDL.define do
30
+ model :user do
31
+ attribute :email, :string, required: true, unique: true
32
+ has_many :posts
33
+ timestamps
34
+ end
35
+
36
+ model :post do
37
+ attribute :title, :string, limit: 120, required: true
38
+ attribute :body, :text
39
+ enum :status, values: [:draft, :published]
40
+ belongs_to :user, foreign_key: true
41
+ has_one_attached :image
42
+ timestamps
43
+ end
44
+ end
45
+ ```
46
+
47
+ ### Load a schema from a file
48
+
49
+ ```ruby
50
+ SDL.load_file "schema.rb"
51
+ ```
52
+
53
+ ### Parse command-line arguments
54
+
55
+ ```ruby
56
+ SDL.parse "user", %w[
57
+ email:required:unique
58
+ posts:has_many
59
+ ]
60
+
61
+ SDL.parse "post", %w[
62
+ title:string{120}:required
63
+ body:text
64
+ status:enum{draft,published}
65
+ user:belongs_to:foreign_key
66
+ image:has_one_attached
67
+ ]
68
+ ```
69
+
70
+ ## Contributing
71
+
72
+ Bug reports and pull requests are welcome on GitHub at https://github.com/rzane/sdl. 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.
73
+
74
+ ## License
75
+
76
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
77
+
78
+ ## Code of Conduct
79
+
80
+ Everyone interacting in the SDL project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/rzane/sdl/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 "sdl"
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,57 @@
1
+ require "sdl/version"
2
+ require "sdl/parser"
3
+ require "sdl/schema"
4
+
5
+ module SDL
6
+
7
+ # A base class for all errors
8
+ class Error < StandardError
9
+ end
10
+
11
+ # Raised when the parser encounters an unrecognized directive
12
+ class ParseError < Error
13
+ end
14
+
15
+ # Raised when models can't be sorted by their dependencies
16
+ class CircularDependencyError < Error
17
+ end
18
+
19
+ # Defines a new schema. The block will be evaluated in the
20
+ # context of a {Schema}
21
+ # @return [Schema]
22
+ #
23
+ # @example
24
+ # SDL.define do
25
+ # model :user do
26
+ # attribute :name, :string
27
+ # end
28
+ # end
29
+ def self.define(&block)
30
+ Schema.new(&block)
31
+ end
32
+
33
+ # Loads a schema from a file. The contents of the file
34
+ # will be evaluated in the context of a {Schema}
35
+ # @return [Schema]
36
+ #
37
+ # @example
38
+ # SDL.load_file("schema.rb")
39
+ def self.load_file(file)
40
+ schema = Schema.new
41
+ schema.instance_eval(File.read(file), file)
42
+ schema
43
+ end
44
+
45
+ # Constructs a model from command-line arguments
46
+ # @raise [ParseError]
47
+ # @return [Model]
48
+ # @see Parser
49
+ #
50
+ # @example
51
+ # SDL.parse("user", ["name", "email:required:unique"])
52
+ def self.parse(name, fields)
53
+ parser = Parser.new
54
+ fields = fields.map { |field| parser.parse(field) }
55
+ Model.new(name, fields: fields)
56
+ end
57
+ end
@@ -0,0 +1,55 @@
1
+ require "sdl/field"
2
+ require "active_support/core_ext/string/inflections"
3
+
4
+ module SDL
5
+ # Base class for all association types
6
+ # @abstract
7
+ class Association < Field
8
+ # The name of the associated model
9
+ # @return [String]
10
+ def model_name
11
+ options.fetch(:model_name, name).to_s
12
+ end
13
+ end
14
+
15
+ # Indicates a one-to-one connection with another {Model}
16
+ class Association::HasOne < Association
17
+ # The type of field
18
+ # @return [Symbol]
19
+ def type
20
+ :has_one
21
+ end
22
+ end
23
+
24
+ # Indicates a one-to-many connection with another {Model}
25
+ class Association::HasMany < Association
26
+ # The type of field
27
+ # @return [Symbol]
28
+ def type
29
+ :has_many
30
+ end
31
+
32
+ # The name of the associated model
33
+ # @return [String]
34
+ def model_name
35
+ options.fetch(:model_name) { name.singularize }.to_s
36
+ end
37
+ end
38
+
39
+ # Indicates a one-to-one connection with another {Model}
40
+ class Association::BelongsTo < Association
41
+ include Field::ColumnOptions
42
+
43
+ # The type of field
44
+ # @return [Symbol]
45
+ def type
46
+ :belongs_to
47
+ end
48
+
49
+ # Should this field have a foreign key?
50
+ # @return [Boolean]
51
+ def foreign_key?
52
+ options.fetch(:foreign_key, false)
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,26 @@
1
+ require "sdl/field"
2
+
3
+ module SDL
4
+ # Base class for all attachment types
5
+ # @abstract
6
+ class Attachment < Field
7
+ end
8
+
9
+ # A file that is attached to a {Model}
10
+ class Attachment::HasOne < Attachment
11
+ # The type of field
12
+ # @return [Symbol]
13
+ def type
14
+ :has_one_attached
15
+ end
16
+ end
17
+
18
+ # A list of files that are attached to a {Model}
19
+ class Attachment::HasMany < Attachment
20
+ # The type of field
21
+ # @return [Symbol]
22
+ def type
23
+ :has_many_attached
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,18 @@
1
+ require "sdl/field"
2
+
3
+ module SDL
4
+ # An attribute of a {Model}
5
+ class Attribute < Field
6
+ include Field::ColumnOptions
7
+
8
+ # The type of field
9
+ # @return [Symbol]
10
+ attr_reader :type
11
+
12
+ # @api private
13
+ def initialize(name, type, **options)
14
+ super(name, options)
15
+ @type = type
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,20 @@
1
+ require "sdl/field"
2
+
3
+ module SDL
4
+ # A field of a {Model} that has a predefined list of possible values
5
+ class Enum < Field
6
+ include Field::ColumnOptions
7
+
8
+ # The type of field
9
+ # @return [Symbol]
10
+ def type
11
+ :enum
12
+ end
13
+
14
+ # The possible values for the enum
15
+ # @return [Array<String>]
16
+ def values
17
+ options.fetch(:values, []).map(&:to_s)
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,119 @@
1
+ require "sdl/types"
2
+
3
+ module SDL
4
+ # A base class for all fields of a model
5
+ # @abstract
6
+ class Field
7
+ # The name of the field
8
+ # @return [String]
9
+ attr_reader :name
10
+
11
+ # All options that were passed to the field
12
+ # @return [Hash]
13
+ attr_reader :options
14
+
15
+ # @api private
16
+ def initialize(name, **options)
17
+ @name = name.to_s
18
+ @options = options
19
+ end
20
+
21
+ # @!method id?
22
+ # Indicates that this is an {Attribute} whose type is `:id`
23
+ # @return [Boolean]
24
+ # @!method string?
25
+ # Indicates that this is an {Attribute} whose type is `:string`
26
+ # @return [Boolean]
27
+ # @!method boolean?
28
+ # Indicates that this is an {Attribute} whose type is `:boolean`
29
+ # @return [Boolean]
30
+ # @!method integer?
31
+ # Indicates that this is an {Attribute} whose type is `:integer`
32
+ # @return [Boolean]
33
+ # @!method float?
34
+ # Indicates that this is an {Attribute} whose type is `:float`
35
+ # @return [Boolean]
36
+ # @!method decimal?
37
+ # Indicates that this is an {Attribute} whose type is `:decimal`
38
+ # @return [Boolean]
39
+ # @!method date?
40
+ # Indicates that this is an {Attribute} whose type is `:date`
41
+ # @return [Boolean]
42
+ # @!method datetime?
43
+ # Indicates that this is an {Attribute} whose type is `:datetime`
44
+ # @return [Boolean]
45
+ # @!method text?
46
+ # Indicates that this is an {Attribute} whose type is `:text`
47
+ # @return [Boolean]
48
+ # @!method binary?
49
+ # Indicates that this is an {Attribute} whose type is `:binary`
50
+ # @return [Boolean]
51
+ # @!method enum?
52
+ # Indicates that this is an {Enum}
53
+ # @return [Boolean]
54
+ # @!method belongs_to?
55
+ # Indicates that this is an {Association::BelongsTo}
56
+ # @return [Boolean]
57
+ # @!method has_one?
58
+ # Indicates that this is an {Association::HasOne}
59
+ # @return [Boolean]
60
+ # @!method has_many?
61
+ # Indicates that this is an {Association::HasMany}
62
+ # @return [Boolean]
63
+ # @!method has_one_attached?
64
+ # Indicates that this is an {Attachment::HasOne}
65
+ # @return [Boolean]
66
+ # @!method has_many_attached?
67
+ # Indicates that this is an {Attachment::HasMany}
68
+ # @return [Boolean]
69
+ TYPES.each do |meth|
70
+ define_method "#{meth}?" do
71
+ type == meth
72
+ end
73
+ end
74
+
75
+ module ColumnOptions
76
+ # Is this field required?
77
+ # @return [Boolean]
78
+ def required?
79
+ options.fetch(:required, false)
80
+ end
81
+
82
+ # A default value for this field
83
+ # @return [Object]
84
+ def default
85
+ options[:default]
86
+ end
87
+
88
+ # A limit for the field
89
+ # @return [Integer]
90
+ def limit
91
+ options[:limit]
92
+ end
93
+
94
+ # A precision for the field
95
+ # @return [Integer]
96
+ def precision
97
+ options[:precision]
98
+ end
99
+
100
+ # A scale for the field
101
+ # @return [Integer]
102
+ def scale
103
+ options[:scale]
104
+ end
105
+
106
+ # Is this field unique?
107
+ # @return [Boolean]
108
+ def unique?
109
+ options.fetch(:unique, false)
110
+ end
111
+
112
+ # Should this field have an index?
113
+ # @return [Boolean]
114
+ def index?
115
+ options.fetch(:index, false)
116
+ end
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,103 @@
1
+ require "sdl/types"
2
+ require "sdl/field"
3
+ require "sdl/attribute"
4
+ require "sdl/enum"
5
+ require "sdl/association"
6
+ require "sdl/attachment"
7
+
8
+ module SDL
9
+ # All fields of a {Model}
10
+ class Fields
11
+ include Enumerable
12
+
13
+ # @api private
14
+ def initialize(fields)
15
+ @fields = fields
16
+ end
17
+
18
+ # Get a field by index
19
+ # @param index [Integer]
20
+ # @return [Field,nil]
21
+ def [](index)
22
+ @fields[index]
23
+ end
24
+
25
+ # Iterate over all fields
26
+ # @yield [Field]
27
+ def each(&block)
28
+ @fields.each(&block)
29
+ end
30
+
31
+ # Get all instances of {Attribute}
32
+ # @return [Array<Attribute>]
33
+ def attributes
34
+ grep Attribute
35
+ end
36
+
37
+ # Get all instances of {Association}
38
+ # @return [Array<Association>]
39
+ def associations
40
+ grep Association
41
+ end
42
+
43
+ # Get all instances of {Attachment}
44
+ # @return [Array<Attachment>]
45
+ def attachments
46
+ grep Attachment
47
+ end
48
+
49
+ # @!method id
50
+ # Get all instances of {Attribute} whose type is `:id`
51
+ # @return [Array<Attribute>]
52
+ # @!method string
53
+ # Get all instances of {Attribute} whose type is `:string`
54
+ # @return [Array<Attribute>]
55
+ # @!method boolean
56
+ # Get all instances of {Attribute} whose type is `:boolean`
57
+ # @return [Array<Attribute>]
58
+ # @!method integer
59
+ # Get all instances of {Attribute} whose type is `:integer`
60
+ # @return [Array<Attribute>]
61
+ # @!method float
62
+ # Get all instances of {Attribute} whose type is `:float`
63
+ # @return [Array<Attribute>]
64
+ # @!method decimal
65
+ # Get all instances of {Attribute} whose type is `:decimal`
66
+ # @return [Array<Attribute>]
67
+ # @!method date
68
+ # Get all instances of {Attribute} whose type is `:date`
69
+ # @return [Array<Attribute>]
70
+ # @!method datetime
71
+ # Get all instances of {Attribute} whose type is `:datetime`
72
+ # @return [Array<Attribute>]
73
+ # @!method text
74
+ # Get all instances of {Attribute} whose type is `:text`
75
+ # @return [Array<Attribute>]
76
+ # @!method binary
77
+ # Get all instances of {Attribute} whose type is `:binary`
78
+ # @return [Array<Attribute>]
79
+ # @!method enum
80
+ # Get all instances of {Enum}
81
+ # @return [Array<Enum>]
82
+ # @!method belongs_to
83
+ # Get all instances of {Association::BelongsTo}
84
+ # @return [Array<Association::BelongsTo>]
85
+ # @!method has_one
86
+ # Get all instances of {Association::HasOne}
87
+ # @return [Array<Assocation::HasOne>]
88
+ # @!method has_many
89
+ # Get all instances of {Association::HasMany}
90
+ # @return [Array<Association::HasMany>]
91
+ # @!method has_one_attached
92
+ # Indicates that this is an {Attachment::HasOne}
93
+ # @return [Array<Attachment::HasOne>]
94
+ # @!method has_many_attached
95
+ # Indicates that this is an {Attachment::HasMany}
96
+ # @return [Array<Attachment::HasMany>]
97
+ TYPES.each do |meth|
98
+ define_method meth do
99
+ select { |field| field.type == meth }
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,138 @@
1
+ require "sdl/fields"
2
+ require "sdl/attribute"
3
+ require "sdl/enum"
4
+ require "sdl/association"
5
+ require "sdl/attachment"
6
+
7
+ module SDL
8
+ class Model
9
+ # Name of the model
10
+ # @return [String]
11
+ attr_reader :name
12
+
13
+ # Any additional options
14
+ # @return [Hash]
15
+ attr_reader :options
16
+
17
+ # @api private
18
+ def initialize(name, fields: [], **options, &block)
19
+ @name = name.to_s
20
+ @fields = fields
21
+ @options = options
22
+ instance_eval(&block) if block_given?
23
+ end
24
+
25
+ # All of the fields that have been registered
26
+ # @return [Fields]
27
+ def fields
28
+ Fields.new(@fields)
29
+ end
30
+
31
+ # Adds an {Attribute} to the model
32
+ # @param name [Symbol]
33
+ # @param type [Symbol]
34
+ # @option options [Boolean] :required
35
+ # @option options [Boolean] :unique
36
+ # @option options [Object] :default
37
+ # @option options [Integer] :limit
38
+ # @option options [Integer] :precision
39
+ # @option options [Integer] :scale
40
+ #
41
+ # @example
42
+ # model :user do
43
+ # attribute :name, :string, required: true
44
+ # end
45
+ def attribute(name, type, **options)
46
+ @fields << Attribute.new(*name, type, **options)
47
+ end
48
+
49
+ # Adds an {Enum} to the model
50
+ # @param name [Symbol]
51
+ # @option options [Array<Symbol>] :values
52
+ # @option options [Boolean] :required
53
+ # @option options [Boolean] :unique
54
+ # @option options [Object] :default
55
+ #
56
+ # @example
57
+ # model :user do
58
+ # enum :status, values: [:accepted, :rejected], required: true
59
+ # end
60
+ def enum(name, **options)
61
+ @fields << Enum.new(name, **options)
62
+ end
63
+
64
+ # Adds an {Association::BelongsTo} to the model
65
+ # @param name [Symbol]
66
+ # @option options [Symbol] :model_name
67
+ # @option options [Boolean] :required
68
+ # @option options [Boolean] :unique
69
+ # @option options [Boolean] :foreign_key
70
+ #
71
+ # @example
72
+ # model :user do
73
+ # belongs_to :organization, required: true
74
+ # end
75
+ def belongs_to(name, **options)
76
+ @fields << Association::BelongsTo.new(name, **options)
77
+ end
78
+
79
+ # Adds an {Association::HasOne} to the model
80
+ # @param name [Symbol]
81
+ # @option options [Symbol] :model_name
82
+ #
83
+ # @example
84
+ # model :user do
85
+ # has_one :profile
86
+ # end
87
+ def has_one(name, **options)
88
+ @fields << Association::HasOne.new(name, **options)
89
+ end
90
+
91
+ # Adds an {Association::HasMany} to the model
92
+ # @param name [Symbol]
93
+ # @option options [Symbol] :model_name
94
+ #
95
+ # @example
96
+ # model :user do
97
+ # has_many :devices
98
+ # end
99
+ def has_many(name, **options)
100
+ @fields << Association::HasMany.new(name, **options)
101
+ end
102
+
103
+ # Adds an {Attachment::HasOne} to the model
104
+ # @param name [Symbol]
105
+ # @option options [Hash]
106
+ #
107
+ # @example
108
+ # model :user do
109
+ # has_one_attached :avatar
110
+ # end
111
+ def has_one_attached(name, **options)
112
+ @fields << Attachment::HasOne.new(name, **options)
113
+ end
114
+
115
+ # Adds an {Attachment::HasMany} to the model
116
+ # @param name [Symbol]
117
+ # @param options [Hash]
118
+ #
119
+ # @example
120
+ # model :product do
121
+ # has_many_attached :images
122
+ # end
123
+ def has_many_attached(name, **options)
124
+ @fields << Attachment::HasMany.new(name, **options)
125
+ end
126
+
127
+ # Adds attributes for +:created_at+ and +:updated_at+ to the model
128
+ #
129
+ # @example
130
+ # model :user do
131
+ # timestamps
132
+ # end
133
+ def timestamps
134
+ attribute :created_at, :datetime, required: true
135
+ attribute :updated_at, :datetime, required: true
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,131 @@
1
+ require "sdl/types"
2
+ require "sdl/field"
3
+ require "sdl/enum"
4
+ require "sdl/attribute"
5
+ require "sdl/association"
6
+ require "sdl/attachment"
7
+ require "active_support/core_ext/string/inflections"
8
+
9
+ module SDL
10
+ # The parser takes a string and converts it to a {Field}.
11
+ # A field is described using a series of directives separated
12
+ # by a colon.
13
+ #
14
+ # Examples:
15
+ #
16
+ # * `title:string{120}:required`
17
+ # * `body:text`
18
+ # * `status:enum{draft,published}`
19
+ # * `user:belongs_to:foreign_key`
20
+ # * `image:has_one_attached`
21
+ #
22
+ # Available directives:
23
+ #
24
+ # * `id`
25
+ # * `string`
26
+ # * `string{limit}`
27
+ # * `boolean`
28
+ # * `integer`
29
+ # * `integer{limit}`
30
+ # * `float`
31
+ # * `decimal`
32
+ # * `decimal{precision,scale}`
33
+ # * `date`
34
+ # * `datetime`
35
+ # * `text`
36
+ # * `text{limit}`
37
+ # * `binary`
38
+ # * `binary{limit}`
39
+ # * `enum{value,...}`
40
+ # * `belongs_to`
41
+ # * `belongs_to{model}`
42
+ # * `has_one`
43
+ # * `has_one{model}`
44
+ # * `has_many`
45
+ # * `has_many{model}`
46
+ # * `has_one_attached`
47
+ # * `has_many_attached`
48
+ # * `unique`
49
+ # * `required`
50
+ # * `index`
51
+ # * `foreign_key`
52
+ # * `default{value}`
53
+ class Parser
54
+ # Parses a string into a {Field}
55
+ # @param value [String]
56
+ # @raise [ParseError] when a directive is not recognized
57
+ # @return [Field]
58
+ def parse(value)
59
+ name, *args = value.split(":")
60
+ name = name.to_sym
61
+
62
+ opts = {type: :string}
63
+ args.each { |arg| parse!(arg, opts) }
64
+ type = opts.delete(:type)
65
+
66
+ # Attempt to coerce the default
67
+ opts[:default] = coerce(opts[:default], type) if opts[:default]
68
+
69
+ if type.is_a?(Symbol)
70
+ Attribute.new(name, type, opts)
71
+ else
72
+ type.new(name, opts)
73
+ end
74
+ end
75
+
76
+ private
77
+
78
+ SEPARATOR = /[,.-]/
79
+ TYPES = /^(#{SCALAR_TYPES.join("|")})$/
80
+ TYPES_WITH_LIMIT = /^(string|text|binary|integer)\{(\d+)\}$/
81
+ TYPES_WITH_PRECISION = /^(decimal)\{(\d+)#{SEPARATOR}(\d+)\}$/
82
+
83
+ ENUM = /^enum\{(.*)\}$/
84
+ ATTACHMENT = /^(has_one|has_many)_attached$/
85
+ ASSOCIATION = /^(belongs_to|has_one|has_many)$/
86
+ ASSOCIATION_WITH_NAME = /^(belongs_to|has_one|has_many)\{(.*)\}$/
87
+
88
+ DEFAULT = /^default\{(.*)\}$/
89
+ MODIFIERS = %w[required unique index foreign_key]
90
+
91
+ def parse!(arg, opts)
92
+ case arg
93
+ when TYPES
94
+ opts[:type] = $1.to_sym
95
+ when TYPES_WITH_LIMIT
96
+ opts[:type] = $1.to_sym
97
+ opts[:limit] = $2.to_i
98
+ when TYPES_WITH_PRECISION
99
+ opts[:type] = $1.to_sym
100
+ opts[:precision] = $2.to_i
101
+ opts[:scale] = $3.to_i
102
+ when ENUM
103
+ opts[:type] = Enum
104
+ opts[:values] = $1.split(SEPARATOR)
105
+ when ASSOCIATION
106
+ opts[:type] = Association.const_get($1.camelize)
107
+ when ASSOCIATION_WITH_NAME
108
+ opts[:type] = Association.const_get($1.camelize)
109
+ opts[:model_name] = $2.to_sym
110
+ when ATTACHMENT
111
+ opts[:type] = Attachment.const_get($1.camelize)
112
+ when DEFAULT
113
+ opts[:default] = $1
114
+ when *MODIFIERS
115
+ opts[arg.to_sym] = true
116
+ else
117
+ raise ParseError, "Unrecognized parameter: #{arg}"
118
+ end
119
+ end
120
+
121
+ def coerce(value, type)
122
+ case type
123
+ when :integer then value.to_i
124
+ when :float then value.to_f
125
+ when :boolean then value.match?(/^true$/)
126
+ else
127
+ value
128
+ end
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,51 @@
1
+ require "tsort"
2
+ require "sdl/model"
3
+
4
+ module SDL
5
+ class Schema
6
+ # All models that have been defined
7
+ # @return [Array<Model>]
8
+ attr_reader :models
9
+
10
+ # @api private
11
+ def initialize(&block)
12
+ @models = []
13
+ instance_eval(&block) if block_given?
14
+ end
15
+
16
+ # Find a model by name
17
+ # @param name [Symbol,String] name of the model to find
18
+ # @return [Model,nil]
19
+ def find_model(name)
20
+ models.find { |m| m.name == name.to_s }
21
+ end
22
+
23
+ # Adds a new {Model} to the schema
24
+ # @param name [Symbol]
25
+ # @param options [Hash]
26
+ #
27
+ # @example
28
+ # model :user do
29
+ # attribute :name, :string
30
+ # end
31
+ def model(name, **options, &block)
32
+ @models << Model.new(name, **options, &block)
33
+ end
34
+
35
+ # Sort all {Model} instances in order of dependency
36
+ # @raise [CircularDependencyError]
37
+ def depsort!
38
+ each_node = models.method(:each)
39
+ each_child = lambda do |model, &block|
40
+ belongs_to = model.fields.belongs_to.map(&:model_name)
41
+ children = models.select { |m| belongs_to.include?(m.name) }
42
+ children.each(&block)
43
+ end
44
+
45
+ @models = TSort.tsort(each_node, each_child)
46
+ @models
47
+ rescue TSort::Cyclic
48
+ raise CircularDependencyError, "The schema contains a circular dependency."
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,23 @@
1
+ module SDL
2
+ SCALAR_TYPES = %i[
3
+ id
4
+ string
5
+ boolean
6
+ integer
7
+ float
8
+ decimal
9
+ date
10
+ datetime
11
+ text
12
+ binary
13
+ ]
14
+
15
+ TYPES = SCALAR_TYPES + %i[
16
+ enum
17
+ belongs_to
18
+ has_one
19
+ has_many
20
+ has_one_attached
21
+ has_many_attached
22
+ ]
23
+ end
@@ -0,0 +1,3 @@
1
+ module SDL
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,34 @@
1
+ lib = File.expand_path("lib", __dir__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require "sdl/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "sdl"
7
+ spec.version = SDL::VERSION
8
+ spec.authors = ["Ray Zane"]
9
+ spec.email = ["raymondzane@gmail.com"]
10
+
11
+ spec.summary = %q{A generic schema definition language.}
12
+ spec.homepage = "https://github.com/rzane/sdl"
13
+ spec.license = "MIT"
14
+
15
+ spec.metadata["homepage_uri"] = spec.homepage
16
+ spec.metadata["source_code_uri"] = "https://github.com/rzane/sdl"
17
+ spec.metadata["documentation_uri"] = "https://rubydoc.info/github/rzane/sdl"
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
23
+ end
24
+ spec.bindir = "exe"
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ["lib"]
27
+
28
+ spec.add_dependency "activesupport", "~> 6.0"
29
+
30
+ spec.add_development_dependency "bundler", "~> 2.0"
31
+ spec.add_development_dependency "rake", "~> 10.0"
32
+ spec.add_development_dependency "rspec", "~> 3.0"
33
+ spec.add_development_dependency "simplecov", "~> 0.17.1"
34
+ end
metadata ADDED
@@ -0,0 +1,141 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: sdl
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Ray Zane
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-12-16 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '6.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '6.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: bundler
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '2.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '2.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rake
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '10.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '10.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rspec
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '3.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '3.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: simplecov
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: 0.17.1
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: 0.17.1
83
+ description:
84
+ email:
85
+ - raymondzane@gmail.com
86
+ executables: []
87
+ extensions: []
88
+ extra_rdoc_files: []
89
+ files:
90
+ - ".gitignore"
91
+ - ".rspec"
92
+ - ".travis.yml"
93
+ - ".yardopts"
94
+ - CODE_OF_CONDUCT.md
95
+ - Gemfile
96
+ - LICENSE.txt
97
+ - README.md
98
+ - Rakefile
99
+ - bin/console
100
+ - bin/setup
101
+ - lib/sdl.rb
102
+ - lib/sdl/association.rb
103
+ - lib/sdl/attachment.rb
104
+ - lib/sdl/attribute.rb
105
+ - lib/sdl/enum.rb
106
+ - lib/sdl/field.rb
107
+ - lib/sdl/fields.rb
108
+ - lib/sdl/model.rb
109
+ - lib/sdl/parser.rb
110
+ - lib/sdl/schema.rb
111
+ - lib/sdl/types.rb
112
+ - lib/sdl/version.rb
113
+ - sdl.gemspec
114
+ homepage: https://github.com/rzane/sdl
115
+ licenses:
116
+ - MIT
117
+ metadata:
118
+ homepage_uri: https://github.com/rzane/sdl
119
+ source_code_uri: https://github.com/rzane/sdl
120
+ documentation_uri: https://rubydoc.info/github/rzane/sdl
121
+ post_install_message:
122
+ rdoc_options: []
123
+ require_paths:
124
+ - lib
125
+ required_ruby_version: !ruby/object:Gem::Requirement
126
+ requirements:
127
+ - - ">="
128
+ - !ruby/object:Gem::Version
129
+ version: '0'
130
+ required_rubygems_version: !ruby/object:Gem::Requirement
131
+ requirements:
132
+ - - ">="
133
+ - !ruby/object:Gem::Version
134
+ version: '0'
135
+ requirements: []
136
+ rubyforge_project:
137
+ rubygems_version: 2.6.14
138
+ signing_key:
139
+ specification_version: 4
140
+ summary: A generic schema definition language.
141
+ test_files: []