formulario 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ae3a7435334b0dbb6c91875b41b9516c31284b501ef528a87aaefcc031be2577
4
+ data.tar.gz: 8c01b7771c45769eefe12e9702c040248ee684e74892e24bc83761dc022c854c
5
+ SHA512:
6
+ metadata.gz: 19f8017da3c0c378cc4aa06972b2af746ba37af627acd3d688aea77a310c451c0465facae22fe5fbee61e99e39532bfeab1c56ee7c39f78886c8b1e6fc416b35
7
+ data.tar.gz: fd226a164aa23ee95a7256791086d6f0c948034ffd7fd3e2afca59f818a69d19e5d192e228ef370472e4ab763823aa72b2e0144635c9cf047dc3bc8ac00d6239
data/.gitignore ADDED
@@ -0,0 +1,11 @@
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
data/.rspec ADDED
@@ -0,0 +1,4 @@
1
+ --format progress
2
+ --color
3
+ --require spec_helper
4
+ --order random
data/.travis.yml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ sudo: false
3
+ language: ruby
4
+ cache: bundler
5
+ rvm:
6
+ - 2.6.3
7
+ before_install: gem install bundler -v 2.0.2
data/CHANGELOG.org ADDED
File without changes
@@ -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 iachetti.federico@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 formulario.gemspec
4
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,55 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ formulario (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ awesome_print (1.8.0)
10
+ byebug (11.0.1)
11
+ coderay (1.1.2)
12
+ diff-lcs (1.3)
13
+ docile (1.3.2)
14
+ json (2.2.0)
15
+ method_source (0.9.2)
16
+ pry (0.12.2)
17
+ coderay (~> 1.1.0)
18
+ method_source (~> 0.9.0)
19
+ pry-byebug (3.7.0)
20
+ byebug (~> 11.0)
21
+ pry (~> 0.10)
22
+ rake (10.5.0)
23
+ rspec (3.8.0)
24
+ rspec-core (~> 3.8.0)
25
+ rspec-expectations (~> 3.8.0)
26
+ rspec-mocks (~> 3.8.0)
27
+ rspec-core (3.8.2)
28
+ rspec-support (~> 3.8.0)
29
+ rspec-expectations (3.8.4)
30
+ diff-lcs (>= 1.2.0, < 2.0)
31
+ rspec-support (~> 3.8.0)
32
+ rspec-mocks (3.8.1)
33
+ diff-lcs (>= 1.2.0, < 2.0)
34
+ rspec-support (~> 3.8.0)
35
+ rspec-support (3.8.2)
36
+ simplecov (0.17.0)
37
+ docile (~> 1.1)
38
+ json (>= 1.8, < 3)
39
+ simplecov-html (~> 0.10.0)
40
+ simplecov-html (0.10.2)
41
+
42
+ PLATFORMS
43
+ ruby
44
+
45
+ DEPENDENCIES
46
+ awesome_print
47
+ bundler (~> 2.0)
48
+ formulario!
49
+ pry-byebug
50
+ rake (~> 10.0)
51
+ rspec (~> 3.0)
52
+ simplecov
53
+
54
+ BUNDLED WITH
55
+ 2.0.2
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Federico Iachetti
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,43 @@
1
+ # Formulario
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/formulario`. 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 'formulario'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install formulario
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 spec` 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]/formulario. 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.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the Formulario project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/formulario/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -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
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "formulario"
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__)
data/bin/setup ADDED
@@ -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,35 @@
1
+ lib = File.expand_path("lib", __dir__)
2
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3
+ require "formulario/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "formulario"
7
+ spec.version = Formulario::VERSION
8
+ spec.authors = ["Federico Iachetti"]
9
+ spec.email = ["iachetti.federico@gmail.com"]
10
+
11
+ spec.summary = %q{Form objects for your project}
12
+ spec.description = %q{Form objects for your project}
13
+ spec.homepage = "https://gitlab.com/fiachetti/formulario"
14
+ spec.license = "MIT"
15
+
16
+ spec.metadata["homepage_uri"] = spec.homepage
17
+ spec.metadata["source_code_uri"] = "https://gitlab.com/fiachetti/formulario"
18
+ spec.metadata["changelog_uri"] = "https://gitlab.com/fiachetti/formulario/blob/d46f675a18c4fbf1d16634a5da343a648af7cf0c/CHANGELOG.org"
19
+
20
+ # Specify which files should be added to the gem when it is released.
21
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
22
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
23
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
24
+ end
25
+ spec.bindir = "exe"
26
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
27
+ spec.require_paths = ["lib"]
28
+
29
+ spec.add_development_dependency "bundler", "~> 2.0"
30
+ spec.add_development_dependency "rake", "~> 10.0"
31
+ spec.add_development_dependency "rspec", "~> 3.0"
32
+ spec.add_development_dependency "awesome_print"
33
+ spec.add_development_dependency "pry-byebug"
34
+ spec.add_development_dependency "simplecov"
35
+ end
@@ -0,0 +1,13 @@
1
+ module Formulario
2
+ class Field
3
+ class Blank < Field
4
+ def initialize(raw_value=nil)
5
+ super(raw_value)
6
+ end
7
+
8
+ def blank?
9
+ true
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,30 @@
1
+ module Formulario
2
+ class Field
3
+ class Boolean < Field
4
+ def self.for(raw_value)
5
+ if raw_value.is_a?(Field)
6
+ raw_value
7
+ else
8
+ build(raw_value)
9
+ end
10
+ end
11
+
12
+ private
13
+
14
+ def self.build(raw_value)
15
+ case get_value(raw_value)
16
+ when true, 'true', 't', '1'
17
+ new true
18
+ when false, 'false', 'f', '0', ''
19
+ new false
20
+ else
21
+ ExceptionalValue.new(raw_value, reasons: ['needs to be boolean'])
22
+ end
23
+ end
24
+
25
+ def self.get_value(raw_value)
26
+ raw_value.to_s.downcase
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,46 @@
1
+ module Formulario
2
+ class Field
3
+ class Collection < Field
4
+ include Enumerable
5
+
6
+ def fields
7
+ raw_value
8
+ end
9
+
10
+ def values
11
+ fields.map(&:value)
12
+ end
13
+ alias :value :values
14
+
15
+ def self.[](type)
16
+ Class.new(self).tap { |typed_class|
17
+ typed_class.field_types = TYPES.fetch(type)
18
+ }
19
+ end
20
+
21
+ def exceptional?
22
+ fields.any?(&:exceptional?)
23
+ end
24
+
25
+ def each(&block)
26
+ fields.each(&block)
27
+ end
28
+
29
+ private
30
+
31
+ def self.build(raw_value)
32
+ new Array(raw_value).map { |value|
33
+ field_types.for(value)
34
+ }
35
+ end
36
+
37
+ def self.field_types
38
+ @field_types ||= Field
39
+ end
40
+
41
+ def self.field_types=(type)
42
+ @field_types = type
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,27 @@
1
+ module Formulario
2
+ class Field
3
+ class Date < DefaultTimeField
4
+
5
+ private
6
+
7
+ def self.base_class
8
+ ::Date
9
+ end
10
+
11
+ def self.allowed_keys
12
+ %i[ year month day ]
13
+ end
14
+
15
+ def self.parse_hash(hash)
16
+ return invalid_keys_exceptional_value(hash) if has_invalid_keys?(hash)
17
+
18
+ now = ::Date.today
19
+ new ::Date.new(
20
+ hash[:year] || now.year,
21
+ hash[:month] || now.month,
22
+ hash[:day] || now.day,
23
+ )
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,32 @@
1
+ require "time"
2
+
3
+ module Formulario
4
+ class Field
5
+ class DefaultTimeField < Field
6
+ private
7
+
8
+ def self.build(raw_value)
9
+ case raw_value
10
+ when base_class
11
+ new raw_value
12
+ when ::Hash
13
+ parse_hash(raw_value)
14
+ when ::String
15
+ new base_class.parse(raw_value)
16
+ end
17
+ end
18
+
19
+ def self.invalid_keys_exceptional_value(hash)
20
+ ExceptionalValue.new(hash,
21
+ reasons: [
22
+ "the only possible keys are: #{allowed_keys.map(&:inspect).join(', ')}"
23
+ ])
24
+ end
25
+
26
+ def self.has_invalid_keys?(hash)
27
+ hash.keys.any? {|key| !allowed_keys.include?(key) }
28
+ end
29
+
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,49 @@
1
+ module Formulario
2
+ class Field
3
+ class ExceptionalValue < Field
4
+ include Enumerable
5
+
6
+ attr_reader :reasons
7
+
8
+ def self.for(raw_value, reasons: Undefined)
9
+ new(raw_value, reasons: reasons)
10
+ end
11
+
12
+
13
+ def exceptional?
14
+ true
15
+ end
16
+
17
+ def inspect
18
+ "#{self.class}[#{value} (#{reasons.join(' | ')})]"
19
+ end
20
+
21
+ def to_a
22
+ reasons
23
+ end
24
+
25
+ def each(&block)
26
+ reasons.each(&block)
27
+ end
28
+
29
+ private
30
+
31
+ def initialize(raw_value, reasons: Undefined)
32
+ the_reasons = reasons == Undefined ? ["is invalid"] : Array(reasons)
33
+
34
+ if raw_value.is_a?(self.class)
35
+ new_reasons = raw_value.reasons.concat(Array(the_reasons))
36
+ value = raw_value.raw_value
37
+ else
38
+ new_reasons = Array(the_reasons)
39
+ value = raw_value
40
+ end
41
+
42
+ @reasons = new_reasons
43
+
44
+ super(value)
45
+ end
46
+
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,85 @@
1
+ module Formulario
2
+ class Field
3
+ TYPES = {
4
+ String => Formulario::Field::String,
5
+ :string => Formulario::Field::String,
6
+ Integer => Formulario::Field::Integer,
7
+ :integer => Formulario::Field::Integer,
8
+ Boolean => Formulario::Field::Boolean,
9
+ :boolean => Formulario::Field::Boolean,
10
+ Time => Formulario::Field::Time,
11
+ :time => Formulario::Field::Time,
12
+ Date => Formulario::Field::Date,
13
+ :date => Formulario::Field::Date,
14
+ Collection => Formulario::Field::Collection,
15
+ :collection => Formulario::Field::Collection,
16
+ :array => Formulario::Field::Collection,
17
+ }
18
+
19
+ attr_reader :raw_value
20
+
21
+ def self.for(raw_value)
22
+ if raw_value.is_a?(Field)
23
+ raw_value
24
+ elsif ::Formulario::Utils.empty?(raw_value)
25
+ Blank.new
26
+ else
27
+ build(raw_value)
28
+ end
29
+ end
30
+
31
+ def self.type_for(field_type)
32
+ type_for = TYPES.fetch(field_type) { field_type }
33
+ if type_for < ::Formulario::Form
34
+ FormField[type_for]
35
+ else
36
+ type_for
37
+ end
38
+ end
39
+
40
+ def exceptional?
41
+ false
42
+ end
43
+
44
+ def blank?
45
+ false
46
+ end
47
+
48
+ def value
49
+ raw_value
50
+ end
51
+
52
+ def to_s
53
+ value.to_s
54
+ end
55
+ alias :to_str :to_s
56
+
57
+ def inspect
58
+ "#{self.class}[#{to_s}]"
59
+ end
60
+
61
+ def ==(other)
62
+ new_other = Field.for(other)
63
+ value == new_other.value
64
+ end
65
+
66
+ private
67
+
68
+ def self.build(raw_value)
69
+ new(raw_value)
70
+ end
71
+
72
+ def initialize(raw_value)
73
+ @raw_value = raw_value
74
+ freeze
75
+ end
76
+
77
+ # TODO: Extract field types
78
+ # TODO: Add
79
+ # Date
80
+ # Time
81
+ # DateTime
82
+ # Boolean
83
+ # Boolean
84
+ end
85
+ end
@@ -0,0 +1,58 @@
1
+ module Formulario
2
+ class Field
3
+ class FormField < Field
4
+ attr_reader :form
5
+
6
+ def self.[](type)
7
+ Class.new(self) do |typed_class|
8
+ typed_class.type = type
9
+ end
10
+ end
11
+
12
+ def self.type
13
+ @type
14
+ end
15
+
16
+ def value
17
+ form.params
18
+ end
19
+
20
+ def exceptional?
21
+ ! form.valid?
22
+ end
23
+
24
+ def fields
25
+ form.fields
26
+ end
27
+
28
+ def [](value)
29
+ fields[value]
30
+ end
31
+
32
+ def initialize(**raw_value)
33
+ @form = self.class.type.new(**raw_value)
34
+ super
35
+ end
36
+
37
+ private
38
+
39
+ def self.build(raw_value)
40
+ raise UndefinedFormFieldType.new unless @type
41
+
42
+ new(raw_value)
43
+ end
44
+
45
+ def self.type=(new_type)
46
+ @type = new_type
47
+ end
48
+
49
+ def method_missing(name, *args, &block)
50
+ return fields[name] if fields.has_key?(name)
51
+
52
+ super
53
+ end
54
+
55
+ UndefinedFormFieldType = Class.new(RuntimeError)
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,4 @@
1
+ module Formulario
2
+ class Id < Integer
3
+ end
4
+ end
@@ -0,0 +1,13 @@
1
+ module Formulario
2
+ class Field
3
+ class Integer < Field
4
+ private
5
+
6
+ def self.build(raw_value)
7
+ new Integer(raw_value)
8
+ rescue ArgumentError, TypeError => e
9
+ ExceptionalValue.new(raw_value, reasons: ['needs to represent an integer'])
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,17 @@
1
+ module Formulario
2
+ class Field
3
+ class String < Field
4
+ private
5
+
6
+ def self.build(raw_value)
7
+ new String(raw_value)
8
+ rescue TypeError => e
9
+ ExceptionalValue.new(raw_value, reasons: ['needs to represent a string'])
10
+ end
11
+
12
+ def initialize(raw_value)
13
+ super
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,31 @@
1
+ module Formulario
2
+ class Field
3
+ class Time < DefaultTimeField
4
+
5
+ private
6
+
7
+ def self.base_class
8
+ ::Time
9
+ end
10
+
11
+ def self.allowed_keys
12
+ %i[ year month day hour minute second timezone ]
13
+ end
14
+
15
+ def self.parse_hash(hash)
16
+ return invalid_keys_exceptional_value(hash) if has_invalid_keys?(hash)
17
+
18
+ now = ::Time.now
19
+ new ::Time.new(
20
+ hash[:year] || now.year,
21
+ hash[:month] || now.month,
22
+ hash[:day] || now.day,
23
+ hash[:hour] || now.hour,
24
+ hash[:minute] || now.min,
25
+ hash[:second] || now.sec,
26
+ hash[:timezone] || now.zone,
27
+ )
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,21 @@
1
+ module Formulario
2
+ class Field
3
+ end
4
+ end
5
+
6
+ require "formulario/fields/blank"
7
+ require "formulario/fields/exceptional_value"
8
+ require "formulario/fields/string"
9
+ require "formulario/fields/integer"
10
+ require "formulario/fields/boolean"
11
+
12
+ require "formulario/fields/default_time_field"
13
+ require "formulario/fields/time"
14
+ require "formulario/fields/date"
15
+
16
+ require "formulario/fields/collection"
17
+ require "formulario/fields/form_field"
18
+
19
+ require "formulario/fields/id"
20
+
21
+ require "formulario/fields/field"
@@ -0,0 +1,149 @@
1
+ module Formulario
2
+ class Form
3
+ def initialize(skip_validations: false, **params)
4
+ __fields.each do |field_name, **options|
5
+ send("#{field_name}=", params.delete(field_name))
6
+ end
7
+
8
+ params.each do |k, v|
9
+ send("#{k}=", v)
10
+ end
11
+
12
+ __validate! unless skip_validations
13
+ end
14
+
15
+ def self.default
16
+ params = __fields.each_with_object({}) { |field, res|
17
+ default_value = field.last[:default]
18
+ res[field.first] = default_value.is_a?(Proc) ? nil : default_value
19
+ }
20
+
21
+ new(skip_validations: true, **params)
22
+ end
23
+
24
+ def __fields
25
+ @__fields ||= {}
26
+ end
27
+
28
+ def params
29
+ __fields.each_with_object({}) { |field_info, res|
30
+ field_name = field_info.first
31
+ options = field_info.last
32
+
33
+ res[field_name] = options[:value].value
34
+ }
35
+ end
36
+
37
+ def fields
38
+ @fields ||= __fields.each_with_object({}) { |field, result|
39
+ result[field.first] = field.last[:value]
40
+ }
41
+ end
42
+
43
+ def valid?
44
+ __fields.none? { |_, value:, **options| value.exceptional? }
45
+ end
46
+
47
+ def error_fields
48
+ @error_fields ||= fields.select { |_, field| field.exceptional? }
49
+ end
50
+
51
+ def errors
52
+ error_fields.transform_values(&:to_a)
53
+ end
54
+
55
+ def on_valid
56
+ yield if valid?
57
+ self
58
+ end
59
+
60
+ def on_invalid
61
+ yield unless valid?
62
+ self
63
+ end
64
+
65
+ private
66
+
67
+ def self.__fields
68
+ @field ||= {}
69
+ end
70
+
71
+ def __fields
72
+ @__fields ||= self.class.__fields
73
+ end
74
+
75
+ def self.field(field_name,
76
+ field_type=Field,
77
+ default: ::Formulario::Field::Blank.new)
78
+
79
+ __fields[field_name.to_sym] = {
80
+ default: default,
81
+ validators: [],
82
+ }
83
+
84
+
85
+ define_method(field_name) do
86
+ __fields.dig(field_name.to_sym, :value)
87
+ end
88
+
89
+ define_method("set_#{field_name}") do |raw_value|
90
+ return raw_value unless Utils.empty?(raw_value)
91
+
92
+ default.is_a?(Proc) ? instance_eval(&default) : default
93
+ end
94
+
95
+ define_method("#{field_name}=") do |raw_value|
96
+ __fields[field_name.to_sym][:value] = Field.type_for(field_type).for(
97
+ send("set_#{field_name}", raw_value)
98
+ )
99
+ end
100
+ end
101
+
102
+ def self.validate(field_name, validator=Undefined,
103
+ message: Undefined, &validation_block)
104
+
105
+ validation_function = case
106
+ when block_given?
107
+ validation_block
108
+ when validator.is_a?(Symbol)
109
+ validator
110
+ when validator.is_a?(::Formulario::Validator)
111
+ validator
112
+ end
113
+
114
+ __fields[field_name][:validators] << {
115
+ validator: validation_function,
116
+ message: message,
117
+ }
118
+ end
119
+
120
+ def __validate!
121
+ __fields.each do |field_name, validators:, value:, **options|
122
+ __fields[field_name][:value] =
123
+ validators.inject(value) do |current_value, validator_hash|
124
+
125
+ validator_block = case validator_hash[:validator]
126
+ when ::Formulario::Validator
127
+ validator_hash[:validator]
128
+ when Symbol
129
+ ::Formulario::Validator.new(&method(validator_hash[:validator]))
130
+ when Proc
131
+ ::Formulario::Validator.new(&validator_hash[:validator])
132
+ end
133
+
134
+ if instance_exec(value: value.value, object: self, field_name: field_name, &validator_block.to_proc).valid?
135
+ current_value
136
+ else
137
+ message = if validator_hash[:validator].is_a?(::Formulario::Validator)
138
+ validator_hash[:validator].message
139
+ end
140
+
141
+ ::Formulario::Field::ExceptionalValue
142
+ .new(current_value,
143
+ reasons: message || validator_hash[:message])
144
+ end
145
+ end
146
+ end
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,9 @@
1
+ module Formulario
2
+ module Utils
3
+ module_function
4
+
5
+ def empty?(object)
6
+ object.nil? || object.to_s.strip.empty?
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,69 @@
1
+ module Formulario
2
+ class Validator
3
+
4
+ def initialize(&validation_block)
5
+ @validation_block = validation_block if block_given?
6
+ end
7
+
8
+ def call(value:, field_name: nil, object: nil)
9
+ @value = value
10
+ @field_name = field_name
11
+ @object = object
12
+ @valid = object.instance_exec(value, &validation_block)
13
+ @validated = true
14
+
15
+ self
16
+ end
17
+
18
+ def to_proc
19
+ method(:call)
20
+ end
21
+
22
+ def valid?
23
+ raise ValidationNotPerformed unless validated?
24
+
25
+ valid
26
+ end
27
+
28
+ def message
29
+ valid? ? '' : failure_text.to_s
30
+ end
31
+
32
+ def on_valid
33
+ yield if valid?
34
+
35
+ self
36
+ end
37
+
38
+ def on_invalid
39
+ yield unless valid?
40
+
41
+ self
42
+ end
43
+
44
+ private
45
+
46
+ attr_reader :value
47
+ attr_reader :field_name
48
+ attr_reader :object
49
+
50
+ attr_reader :valid
51
+ attr_reader :validated
52
+ alias :validated? :validated
53
+
54
+ def validate(value)
55
+ true
56
+ end
57
+
58
+ def validation_block
59
+ @validation_block ||= method(:validate)
60
+ end
61
+
62
+
63
+ def failure_text
64
+ 'is invalid'
65
+ end
66
+
67
+ ValidationNotPerformed = Class.new(RuntimeError)
68
+ end
69
+ end
@@ -0,0 +1,3 @@
1
+ module Formulario
2
+ VERSION = "0.1.0"
3
+ end
data/lib/formulario.rb ADDED
@@ -0,0 +1,9 @@
1
+ module Formulario
2
+ Undefined = Class.new
3
+ end
4
+
5
+ require "formulario/version"
6
+ require "formulario/utils"
7
+ require "formulario/fields"
8
+ require "formulario/validator"
9
+ require "formulario/form"
metadata ADDED
@@ -0,0 +1,161 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: formulario
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Federico Iachetti
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2019-08-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '2.0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '2.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: awesome_print
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: pry-byebug
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: simplecov
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ description: Form objects for your project
98
+ email:
99
+ - iachetti.federico@gmail.com
100
+ executables: []
101
+ extensions: []
102
+ extra_rdoc_files: []
103
+ files:
104
+ - ".gitignore"
105
+ - ".rspec"
106
+ - ".travis.yml"
107
+ - CHANGELOG.org
108
+ - CODE_OF_CONDUCT.md
109
+ - Gemfile
110
+ - Gemfile.lock
111
+ - LICENSE.txt
112
+ - README.md
113
+ - Rakefile
114
+ - bin/console
115
+ - bin/setup
116
+ - formulario.gemspec
117
+ - lib/formulario.rb
118
+ - lib/formulario/fields.rb
119
+ - lib/formulario/fields/blank.rb
120
+ - lib/formulario/fields/boolean.rb
121
+ - lib/formulario/fields/collection.rb
122
+ - lib/formulario/fields/date.rb
123
+ - lib/formulario/fields/default_time_field.rb
124
+ - lib/formulario/fields/exceptional_value.rb
125
+ - lib/formulario/fields/field.rb
126
+ - lib/formulario/fields/form_field.rb
127
+ - lib/formulario/fields/id.rb
128
+ - lib/formulario/fields/integer.rb
129
+ - lib/formulario/fields/string.rb
130
+ - lib/formulario/fields/time.rb
131
+ - lib/formulario/form.rb
132
+ - lib/formulario/utils.rb
133
+ - lib/formulario/validator.rb
134
+ - lib/formulario/version.rb
135
+ homepage: https://gitlab.com/fiachetti/formulario
136
+ licenses:
137
+ - MIT
138
+ metadata:
139
+ homepage_uri: https://gitlab.com/fiachetti/formulario
140
+ source_code_uri: https://gitlab.com/fiachetti/formulario
141
+ changelog_uri: https://gitlab.com/fiachetti/formulario/blob/d46f675a18c4fbf1d16634a5da343a648af7cf0c/CHANGELOG.org
142
+ post_install_message:
143
+ rdoc_options: []
144
+ require_paths:
145
+ - lib
146
+ required_ruby_version: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - ">="
149
+ - !ruby/object:Gem::Version
150
+ version: '0'
151
+ required_rubygems_version: !ruby/object:Gem::Requirement
152
+ requirements:
153
+ - - ">="
154
+ - !ruby/object:Gem::Version
155
+ version: '0'
156
+ requirements: []
157
+ rubygems_version: 3.0.6
158
+ signing_key:
159
+ specification_version: 4
160
+ summary: Form objects for your project
161
+ test_files: []