gourami 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: 6350a0c25f3ae177cd9f7f1679421265ca935c28
4
+ data.tar.gz: 67acb125ddd4c6641bf804cc3ceb1f7330b9f09a
5
+ SHA512:
6
+ metadata.gz: 941e297d65e2e2fda1c4636c3662360293f9bd2a0e9789446e397446ff176330fe4944fc16ce69867f531dd92a395b9a6e848d485e248670c1b1f60bb1f2c5dc
7
+ data.tar.gz: 913a0865ffd2357dab99423ac30ce46c737ebf74929404e245fb28c4fe92e76e1f9326d06e72767129d00b3067bb2de2cbf256787fd648e9257ce5f08c7db7a9
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.1.8
5
+ before_install: gem install bundler -v 1.13.5
@@ -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 mark.allen@vydia.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,3 @@
1
+ source "https://rubygems.org"
2
+
3
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 TSMMark
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,37 @@
1
+ # Gourami
2
+
3
+ Keep your Routes, Controllers and Models thin.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your Gemfile:
8
+
9
+ ```ruby
10
+ gem 'gourami'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install gourami
20
+
21
+ ## Usage
22
+
23
+ TODO: Write usage instructions here
24
+
25
+ ## Development
26
+
27
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
28
+
29
+ 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).
30
+
31
+ ## Contributing
32
+
33
+ Bug reports and pull requests are welcome on GitHub at https://github.com/TSMMark/gourami. 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.
34
+
35
+ ## License
36
+
37
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
@@ -0,0 +1,11 @@
1
+ require "bundler/gem_tasks"
2
+ require "rake/testtask"
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << "test"
6
+ t.libs << "lib"
7
+ t.test_files = FileList["spec/**/*_spec.rb"]
8
+ end
9
+
10
+ task :spec => :test
11
+ task :default => :test
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "gourami"
5
+ require "irb"
6
+ IRB.start
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env bash
2
+
3
+ set -euo pipefail
4
+ IFS=$'\n\t'
5
+ set -vx
6
+
7
+ bundle install
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "gourami/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "gourami"
8
+ spec.version = Gourami::VERSION
9
+ spec.authors = ["TSMMark"]
10
+ spec.email = ["9thousand@gmail.com"]
11
+
12
+ spec.summary = %q{Keep your Routes, Controllers and Models thin.}
13
+ spec.description = %q{Create Plain Old Ruby Objects that take attributes, validate them, and perform an action.}
14
+ spec.homepage = "http://github.com/TSMMark/gourami"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.13"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "minitest", "~> 5.0"
27
+ end
@@ -0,0 +1,11 @@
1
+ module Gourami
2
+ end
3
+
4
+ require "gourami/attributes"
5
+ require "gourami/coercer"
6
+ require "gourami/form"
7
+ require "gourami/formatting_constants"
8
+ require "gourami/required_attribute_error"
9
+ require "gourami/validation_error"
10
+ require "gourami/validations"
11
+ require "gourami/version"
@@ -0,0 +1,180 @@
1
+ module Gourami
2
+ module Attributes
3
+
4
+ module ClassMethods
5
+ # Copy parent attributes to inheriting class.
6
+ #
7
+ # @param klass [Class]
8
+ def inherited(klass)
9
+ super(klass)
10
+ klass.instance_variable_set(:@attributes, attributes.dup)
11
+ end
12
+
13
+ # Define an attribute for the form.
14
+ #
15
+ # @param name
16
+ # The Symbol attribute name.
17
+ # @option options
18
+ # The type of this attribute. Can be any of :string, :integer,
19
+ # :float, :array, :hash or :boolean.
20
+ # @block default_block
21
+ # If provided, the block will be applied to options as the :default
22
+ def attribute(name, options = {}, &default_block)
23
+ options = options.dup
24
+ options[:default] = default_block if block_given?
25
+
26
+ unless options[:skip_reader]
27
+ define_method(:"#{name}") do
28
+ value = instance_variable_get(:"@#{name}")
29
+ default = options[:default]
30
+
31
+ if value.nil? && default
32
+ default.respond_to?(:call) ? instance_exec(&default) : default
33
+ else
34
+ value
35
+ end
36
+ end
37
+ end
38
+
39
+ # Define external setter.
40
+ define_method(:"#{name}=") do |value|
41
+ provided_attributes_names[name.to_s] = options
42
+ send(:"_#{name}=", value)
43
+ end
44
+
45
+ # Define internal setter.
46
+ define_method(:"_#{name}=") do |value|
47
+ value = setter_filter(name, value, options)
48
+ instance_variable_set(:"@#{name}", value)
49
+ end
50
+ private :"_#{name}="
51
+
52
+ case options[:type]
53
+ when :boolean
54
+ define_method(:"#{name}?") do
55
+ !!send(name)
56
+ end
57
+ end
58
+
59
+ attributes[name] = options
60
+ end
61
+
62
+ # Define the main record of this form (optional).
63
+ # Record may be called with form_instance.record
64
+ #
65
+ # @param name
66
+ # The Symbol attribute name.
67
+ # @option options [Class]
68
+ # The Class of the type of this attribute. Can be any of String, Integer,
69
+ # Float, Array, Hash or :boolean.
70
+ def record(name, options = {})
71
+ define_method(:record) do
72
+ send(name)
73
+ end
74
+ attribute(name, options.merge(:skip => true))
75
+ end
76
+
77
+ # Retrieve the list of attributes of the form.
78
+ #
79
+ # @return [Hash]
80
+ # The class attributes hash.
81
+ def attributes
82
+ @attributes ||= {}
83
+ end
84
+ end
85
+
86
+ # Extend ClassMethods into including class.
87
+ #
88
+ # @param klass [Class]
89
+ def self.included(klass)
90
+ klass.send(:extend, ClassMethods)
91
+ end
92
+
93
+ # Initialize a new Gourami::Form form.
94
+ #
95
+ # @param attrs [Hash]
96
+ # The attributes values to use for the new instance.
97
+ def initialize(attrs = {})
98
+ set_attributes(attrs)
99
+ end
100
+
101
+ # Set the attributes belonging to the form.
102
+ # Overrides ALL existing attributes,
103
+ # including ones not provided in the `attrs` argument.
104
+ #
105
+ # @param attrs [Hash<[String, Symbol], Object>]
106
+ def set_attributes(attrs)
107
+ return unless attrs.kind_of?(Hash)
108
+
109
+ attrs = attrs.map { |k, v| [k.to_s, v] }.to_h
110
+
111
+ self.class.attributes.each do |name, opts = {}|
112
+ name = name.to_s
113
+
114
+ if attrs.key?(name)
115
+ value = attrs[name]
116
+ provided_attributes_names[name] = opts
117
+ end
118
+
119
+ if value.nil? && opts[:required] && !opts[:default]
120
+ # TODO: Consider raising this during validate or perform instead.
121
+ raise RequiredAttributeError, "#{name.inspect} is a required attribute of #{self.class.to_s}"
122
+ end
123
+
124
+ send(:"_#{name}=", value)
125
+ end
126
+ end
127
+
128
+ # Offer descendants the opportunity to modify attribute values as they are set.
129
+ #
130
+ # @param attribute_name [Symbol] name of the attribute
131
+ # @param value [*] the value as it is passed into the setter
132
+ # @param options [Hash] attribute options
133
+ #
134
+ # @return [*]
135
+ def setter_filter(attribute_name, value, options)
136
+ value
137
+ end
138
+
139
+ # Get the all attributes with its values of the current form except the attributes labeled with skip.
140
+ #
141
+ # @return [Hash<Symbol, Object>]
142
+ def attributes
143
+ unskipped_attributes = self.class.attributes.reject { |_, opts| opts[:skip] }
144
+ attributes_hash_from_attributes_options(unskipped_attributes)
145
+ end
146
+
147
+ # Get the all attributes with its values of the current form.
148
+ #
149
+ # @return [Hash<Symbol, Object>]
150
+ def all_attributes
151
+ attributes_hash_from_attributes_options(self.class.attributes)
152
+ end
153
+
154
+ def provided_attributes
155
+ unskipped_attributes = self.class.attributes.reject { |_, opts| opts[:skip] }
156
+ provided_attributes = unskipped_attributes.select { |name, _| attribute_provided?(name) }
157
+ attributes_hash_from_attributes_options(provided_attributes)
158
+ end
159
+
160
+ def provided_attributes_names
161
+ @provided_attributes_names ||= {}
162
+ end
163
+
164
+ def attribute_provided?(attribute_name)
165
+ provided_attributes_names.key?(attribute_name.to_s)
166
+ end
167
+
168
+ # Get the all attributes given a hash of attributes with options.
169
+ #
170
+ # @param attributes_options [Hash<Symbol, Hash>] attributes with options
171
+ #
172
+ # @return [Hash<Symbol, Object>]
173
+ def attributes_hash_from_attributes_options(attributes_options)
174
+ attributes_options.each_with_object({}) do |(name, _), attrs|
175
+ attrs[name] = send(name)
176
+ end
177
+ end
178
+
179
+ end
180
+ end
@@ -0,0 +1,211 @@
1
+ module Gourami
2
+ module Coercer
3
+
4
+ # When it is being set, coerce the value of the attribute
5
+ # according to the :type option.
6
+ #
7
+ # @param attribute_name [Symbol] name of the attribute
8
+ # @param value [*] the value as it is passed into the setter
9
+ # @param options [Hash] attribute options
10
+ #
11
+ # @return [*]
12
+ def setter_filter(attribute_name, value, options)
13
+ type = options[:type]
14
+ coercer_method_name = :"coerce_#{type}"
15
+ if type
16
+ value = send(coercer_method_name, value, options)
17
+ end
18
+
19
+ super(attribute_name, value, options)
20
+ end
21
+
22
+ # Coerce the value into a String.
23
+ #
24
+ # @param value [Object]
25
+ # @option allow_nil [Boolean] (true)
26
+ # @option upcase [Boolean] (false)
27
+ # @option strip [Boolean] (false)
28
+ #
29
+ # @return [String, nil]
30
+ def coerce_string(value, options = {})
31
+ return nil if value.nil? && options.fetch(:allow_nil, true)
32
+
33
+ value = value.to_s.dup.force_encoding(Encoding::UTF_8)
34
+ value.strip! if options[:strip]
35
+ value.upcase! if options[:upcase]
36
+
37
+ value
38
+ end
39
+
40
+ # Corce the value into true or false.
41
+ #
42
+ # @param value [Object]
43
+ # @option allow_nil [Boolean] (false)
44
+ #
45
+ # @return [Boolean, nil]
46
+ def coerce_boolean(value, options = {})
47
+ return nil if options[:allow_nil] && (value.nil? || value == "")
48
+ return false if value.to_s.strip == "false"
49
+ !!value && !coerce_string(value).strip.empty?
50
+ end
51
+
52
+ # Coerce the value into an Array.
53
+ #
54
+ # @param value [Object]
55
+ # The value to be coerced.
56
+ # @option element_type [Symbol, Hash] (nil)
57
+ # The type of the value to coerce each element of the array, if nil
58
+ # no coercion is performed.
59
+ # If a Hash is given, it is passed as options to the coercer.
60
+ #
61
+ # TODO docs for the rest of the options
62
+ #
63
+ # @return [Array]
64
+ # The coerced Array.
65
+ def coerce_array(value, options = {})
66
+ element_type = options[:element_type]
67
+ value = value.values if value.kind_of?(Hash)
68
+
69
+ if options[:split_by] && value.kind_of?(String)
70
+ value = value.split(options[:split_by]).map(&:strip)
71
+ end
72
+
73
+ if value.kind_of?(Array)
74
+ if element_type
75
+ if element_type.kind_of?(Hash)
76
+ element_type_options = element_type
77
+ element_type = element_type[:type]
78
+ else
79
+ element_type_options = {}
80
+ end
81
+
82
+ coercer_method_name = :"coerce_#{element_type}"
83
+ value.map do |array_element|
84
+ send(coercer_method_name, array_element, element_type_options)
85
+ end
86
+ else
87
+ value
88
+ end
89
+ else
90
+ []
91
+ end
92
+ end
93
+
94
+ # Coerce the value into a Float.
95
+ #
96
+ # @param value [Object]
97
+ #
98
+ # @return [Float, nil]
99
+ def coerce_float(value, options = {})
100
+ Float(value) rescue nil
101
+ end
102
+
103
+ # Coerce the value into an international phone String.
104
+ #
105
+ # @param value [Object]
106
+ # The value to be coerced.
107
+ #
108
+ # @return [String, nil]
109
+ def coerce_phone(value, options = {})
110
+ value ? coerce_string(value).upcase.gsub(/[^+0-9A-Z]/,"") : nil
111
+ end
112
+
113
+ # Coerce the value into a Hash.
114
+ #
115
+ # @param value [Object]
116
+ # The value to be coerced.
117
+ # @option options :key_type [Symbol, Callable] (nil)
118
+ # The type of the hash keys to coerce, no coersion if value is nil.
119
+ # @option options :value_type [Symbol, Callable] (nil)
120
+ # The type of the hash values to coerce, no coersion if value is nil.
121
+ #
122
+ # @return [Hash]
123
+ # The coerced Hash.
124
+ def coerce_hash(value, options = {})
125
+ hash_key_type = options[:key_type]
126
+ hash_value_type = options[:value_type]
127
+ if value.kind_of?(Hash) || value.kind_of?(Sequel::Postgres::JSONHash)
128
+ value.each_with_object({}) do |(key, value), coerced_hash|
129
+ key_type = hash_key_type.respond_to?(:call) ? hash_key_type.call(key, value) : hash_key_type
130
+ key = send("coerce_#{key_type}", key) if key_type
131
+
132
+ value_type = hash_value_type.respond_to?(:call) ? hash_value_type.call(key, value) : hash_value_type
133
+ value = send("coerce_#{value_type}", value) if value_type
134
+ coerced_hash[key] = value
135
+ end
136
+ else
137
+ {}
138
+ end
139
+ end
140
+
141
+ # Coerce the value into an Integer.
142
+ #
143
+ # @param value [Object]
144
+ # The value to be coerced.
145
+ #
146
+ # @return [Integer, nil]
147
+ # An Integer if the value can be coerced or nil otherwise.
148
+ def coerce_integer(value, options = {})
149
+ value = value.to_s
150
+ if value.match(/\A0|[1-9]\d*\z/)
151
+ value.to_i
152
+ else
153
+ nil
154
+ end
155
+ end
156
+
157
+ # Coerce the value into a Date.
158
+ #
159
+ # @param value [Object]
160
+ # The value to be coerced.
161
+ #
162
+ # @return [Date, nil]
163
+ # A Date if the value can be coerced or nil otherwise.
164
+ def coerce_date(value, options = {})
165
+ value = coerce_string(value, options)
166
+ return nil if value.nil?
167
+ begin
168
+ Date.strptime(value, "%Y-%m-%d")
169
+ rescue ArgumentError
170
+ nil
171
+ end
172
+ end
173
+
174
+ # Coerce the value into a Time.
175
+ #
176
+ # @param value [Object]
177
+ # The value to be coerced.
178
+ #
179
+ # @return [Time, nil]
180
+ # A Time if the value can be coerced or nil otherwise.
181
+ def coerce_time(value, options = {})
182
+ value = coerce_string(value, options)
183
+ return nil if !value || value.empty?
184
+
185
+ begin
186
+ Time.parse(value).utc
187
+ rescue ArgumentError
188
+ nil
189
+ end
190
+ end
191
+
192
+ # Coerce the value into a File. For the value to be successfully accepted as,
193
+ # it should be a hash containing the :filename (String) and :tempfile
194
+ # (File).
195
+ #
196
+ # @param value [Object]
197
+ #
198
+ # @return [Hash, nil]
199
+ # The hash will contain the file String :filename and the File :tempfile,
200
+ # or nil otherwise.
201
+ def coerce_file(value, options = {})
202
+ if value.kind_of?(Hash) && !value[:filename].to_s.empty?
203
+ tempfile = value[:tempfile]
204
+ if tempfile.kind_of?(File) || tempfile.kind_of?(Tempfile)
205
+ value
206
+ end
207
+ end
208
+ end
209
+
210
+ end
211
+ end
@@ -0,0 +1,96 @@
1
+ module Gourami
2
+ module Extensions
3
+ module Resources
4
+
5
+ # Return a deeply nested Hash which allows you to identify errors by resource.
6
+ #
7
+ # @return [Hash<Symbol>]
8
+ #
9
+ # @example
10
+ # resource_errors
11
+ # # => {
12
+ # # :social_broadcasts => {
13
+ # # :"facebook_page-41" => {
14
+ # # :trim_start_time => [:is_invalid, :is_too_short],
15
+ # # :trim_end_time => [:is_invalid]
16
+ # # },
17
+ # # :"youtube_account-42" => {
18
+ # # :title => [:is_too_short]
19
+ # # }
20
+ # # },
21
+ # # :another_resource => {
22
+ # # :"other_resource_id-12" => {
23
+ # # :something => [:is_too_long]
24
+ # # }
25
+ # # }
26
+ # # }
27
+ #
28
+ # resource_errors[:social_broadcasts]
29
+ # # => {
30
+ # # :"facebook_page-41" => {
31
+ # # :trim_start_time => [:is_invalid, :is_too_short],
32
+ # # :trim_end_time => [:is_invalid]
33
+ # # },
34
+ # # :"youtube_account-42" => {
35
+ # # :title => [:is_too_short]
36
+ # # }
37
+ # # }
38
+ #
39
+ # resource_errors[:social_broadcasts][:"facebook_page-41"]
40
+ # # => {
41
+ # # :trim_start_time => [:is_invalid, :is_too_short],
42
+ # # :trim_end_time => [:is_invalid]
43
+ # # }
44
+ #
45
+ # resource_errors[:social_broadcasts][:"facebook_page-41"][:trim_start_time]
46
+ # # => [:is_invalid, :is_too_short]
47
+ def resource_errors
48
+ @resource_errors ||= Hash.new do |resource_errors, resource_name|
49
+ resource_errors[resource_name] = Hash.new do |resource_uids, resource_uid|
50
+ resource_uids[resource_uid] = Hash.new do |attributes, attribute_name|
51
+ attributes[attribute_name] = []
52
+ end
53
+ end
54
+ end
55
+ end
56
+
57
+ # TODO: YARD
58
+ def resource_has_errors?(resource_namespace, resource_uid)
59
+ resource_errors[resource_namespace, resource_uid.to_s].values.map(&:flatten).any?
60
+ end
61
+
62
+ # TODO: YARD
63
+ def resource_attribute_has_errors?(resource_namespace, resource_uid, attribute_name)
64
+ resource_errors[resource_namespace][resource_uid.to_s][attribute_name].any?
65
+ end
66
+
67
+ # Append an error to the given attribute for a resource.
68
+ # TODO: consider coercing attribute_name `.to_s` too.
69
+ #
70
+ # @param resource_namespace [Symbol]
71
+ # @param resource_uid [String]
72
+ # @param attribute_name [Symbol]
73
+ # @param error [Symbol, String]
74
+ # The error identifier.
75
+ def append_resource_error(resource_namespace, resource_uid, attribute_name, error)
76
+ resource_errors[resource_namespace][resource_uid.to_s][attribute_name] << error
77
+ end
78
+
79
+ # Determine if current form instance is valid by running the validations
80
+ # specified on #validate.
81
+ #
82
+ # @return [Boolean]
83
+ def any_errors?
84
+ super || any_resource_errors?
85
+ end
86
+
87
+ # Return true if any resources by any uids have any errors.
88
+ #
89
+ # @return [Boolean]
90
+ def any_resource_errors?
91
+ resource_errors.values.flat_map(&:values).map(&:values).flatten.any?
92
+ end
93
+
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,92 @@
1
+ require_relative "./attributes"
2
+ require_relative "./validations"
3
+ require_relative "./coercer"
4
+
5
+ module Gourami
6
+ # Base Form for doing actions based on the attributes specified.
7
+ # This class has to be inherited by different forms, each performing a
8
+ # different action. If needed, #validate method can be overridden if
9
+ # necessary.
10
+ #
11
+ # @example
12
+ #
13
+ # class LogIn < Gourami::Form
14
+ #
15
+ # attribute(:username, :type => :string)
16
+ # attribute(:password, :type => :string)
17
+ #
18
+ # def validate
19
+ # unless valid_login?
20
+ # append_error(:username, :invalid_credentials)
21
+ # end
22
+ # end
23
+ #
24
+ # def perform
25
+ # User.create(attributes)
26
+ # end
27
+ #
28
+ # private
29
+ #
30
+ # def valid_login?
31
+ # user = User.first(:username => username)
32
+ # user && check_password_secure(user.password, password)
33
+ # end
34
+ #
35
+ # end
36
+ #
37
+ # @example
38
+ #
39
+ # class UpdateUser < Gourami::Form
40
+ #
41
+ # VALID_TYPES = %w[buyer seller]
42
+ #
43
+ # record(:user, :skip => true)
44
+ # attribute(:username, :type => :string)
45
+ # attribute(:first_name, :type => :string)
46
+ # attribute(:percentage, :type => :integer)
47
+ # attribute(:type, :type => :string)
48
+ #
49
+ # def validate
50
+ # validate_presence(:username)
51
+ # validate_length(:username, :min => 2, :max => 64)
52
+ #
53
+ # validate_presence(:first_name)
54
+ #
55
+ # validate_presence(:percantage)
56
+ # validate_range(:percentage, :min => 0, :max => 100)
57
+ #
58
+ # validate_presence(:type)
59
+ # validate_inclusion(:type, VALID_TYPES)
60
+ # end
61
+ #
62
+ # def perform
63
+ # user.update(attributes)
64
+ # end
65
+ #
66
+ # end
67
+ #
68
+ # # Usage of the new form class:
69
+ #
70
+ # form = UpdateUser.new({
71
+ # :user => User.first,
72
+ # :username => "WeijieWorld",
73
+ # :first_name => "Weijie",
74
+ # :percentage => "100",
75
+ # :type => "buyer"
76
+ # })
77
+ #
78
+ # if form.valid?
79
+ # form.perform
80
+ # # Do something else
81
+ # else
82
+ # # Do something else
83
+ # end
84
+ #
85
+ class Form
86
+
87
+ include Gourami::Attributes
88
+ include Gourami::Validations
89
+ include Gourami::Coercer
90
+
91
+ end
92
+ end
@@ -0,0 +1,13 @@
1
+ module Gourami
2
+ module FormattingConstants
3
+
4
+ EMAIL_FORMAT = (/\A
5
+ ([0-9a-zA-Z\.][-\w\+\.]*)@
6
+ ([0-9a-zA-Z_][-\w]*[0-9a-zA-Z]*\.)+[a-zA-Z]{2,9}\z/x).freeze
7
+
8
+ ISRC_FORMAT = (/\A[a-zA-Z]{2}[a-zA-Z0-9]{5}[0-9]{5}\z/).freeze
9
+
10
+ HEX_COLOR_FORMAT = (/^#([A-F0-9]{3}|[A-F0-9]{6})$/i).freeze
11
+
12
+ end
13
+ end
@@ -0,0 +1,4 @@
1
+ module Gourami
2
+ class RequiredAttributeError < StandardError
3
+ end
4
+ end
@@ -0,0 +1,35 @@
1
+ module Gourami
2
+ class ValidationError < StandardError
3
+
4
+ def self.stringify_errors(errors)
5
+ [].tap do |array|
6
+ errors.each do |field, error|
7
+ array.push("#{field}: #{error}")
8
+ end
9
+ end
10
+ end
11
+
12
+ # !@attribute [r] errors
13
+ # @return [Hash<Symbol, Array>]
14
+ attr_reader :errors
15
+
16
+ # Initialize the Gourami::ValidationError.
17
+ #
18
+ # @param errors [Hash<Symbol, Array>]
19
+ def initialize(errors)
20
+ @errors = errors
21
+ super(message)
22
+ end
23
+
24
+ def message
25
+ @message ||= "Validation failed with errors: #{stringify_errors.join("\n")}"
26
+ end
27
+
28
+ private
29
+
30
+ def stringify_errors
31
+ ValidationError.stringify_errors(errors)
32
+ end
33
+
34
+ end
35
+ end
@@ -0,0 +1,214 @@
1
+ require_relative "./formatting_constants"
2
+
3
+ module Gourami
4
+ module Validations
5
+
6
+ include Gourami::FormattingConstants
7
+
8
+ # Validate and perform the form actions. If any errors come up during the
9
+ # validation or the #perform method, raise an exception with the errors.
10
+ #
11
+ # @raise [Gourami::ValidationError]
12
+ def perform!
13
+ if valid?
14
+ returned = perform
15
+ end
16
+
17
+ if any_errors?
18
+ raise ValidationError.new(errors)
19
+ end
20
+
21
+ returned
22
+ end
23
+
24
+ # Get the current form errors Hash.
25
+ #
26
+ # @return [Hash<Symbol, nil>, Array<Symbol, String>]
27
+ # The errors Hash, having the Symbol attribute names as keys and an
28
+ # array of errors (Symbols) as the value.
29
+ def errors
30
+ @errors ||= Hash.new { |hash, key| hash[key] = [] }
31
+ end
32
+
33
+ # Determine if current form instance is valid by running the validations
34
+ # specified on #validate.
35
+ #
36
+ # @return [Boolean]
37
+ def valid?
38
+ errors.clear
39
+ validate
40
+ !any_errors?
41
+ end
42
+
43
+ # Return true if there given attribute has any errors.
44
+ def attribute_has_errors?(attribute_name)
45
+ errors[attribute_name.to_sym].any?
46
+ end
47
+
48
+ # Return true if there are any errors.
49
+ def any_errors?
50
+ errors.reject{ |k,v| v.empty? }.any?
51
+ end
52
+
53
+ # Append an error to the given attribute.
54
+ #
55
+ # @param attribute_name [Symbol, nil] nil for base
56
+ # @param error [Symbol, String]
57
+ # The error identifier.
58
+ def append_error(attribute_name, error)
59
+ errors[attribute_name] << error
60
+ end
61
+
62
+ # Validate the presence of the attribute value. If the value is nil or
63
+ # false append the :cant_be_empty error to the attribute.
64
+ #
65
+ # @param attribute_name [Symbol]
66
+ def validate_presence(attribute_name, message = nil)
67
+ value = send(attribute_name)
68
+ if !value || value.to_s.strip.empty?
69
+ append_error(attribute_name, message || :cant_be_empty)
70
+ end
71
+ end
72
+
73
+ # Validate the uniqueness of the attribute value. The uniqueness is
74
+ # determined by the block given. If the value is not unique, append the
75
+ # :is_duplicated error to the attribute.
76
+ #
77
+ # @param attribute_name [Symbol]
78
+ # @param block [Proc]
79
+ # A block to determine if a given value is unique or not. It receives
80
+ # the value and returns true if the value is unique.
81
+ def validate_uniqueness(attribute_name, message = nil, &block)
82
+ value = attributes[attribute_name]
83
+ unless block.call(value)
84
+ append_error(attribute_name, message || :is_duplicated)
85
+ end
86
+ end
87
+
88
+ # Validate the email format. If the value does not match the email format,
89
+ # append the :is_invalid error to the attribute.
90
+ #
91
+ # @param attribute_name [Symbol]
92
+ def validate_email_format(attribute_name, message = nil)
93
+ validate_format(attribute_name, EMAIL_FORMAT, message)
94
+ end
95
+
96
+ def validate_isrc_format(attribute_name, message = nil)
97
+ validate_format(attribute_name, ISRC_FORMAT, message)
98
+ end
99
+
100
+ def validate_color_format(attribute_name, message = nil)
101
+ validate_format(attribute_name, HEX_COLOR_FORMAT, message)
102
+ end
103
+
104
+ # Validate the format of the attribute value. If the value does not match
105
+ # the regexp given, append :is_invalid error to the attribute.
106
+ #
107
+ # @param attribute_name [Symbol]
108
+ # @param format [Regexp]
109
+ def validate_format(attribute_name, format, message = nil)
110
+ value = attributes[attribute_name]
111
+ if value && !(format =~ value)
112
+ append_error(attribute_name, message || :is_invalid)
113
+ end
114
+ end
115
+
116
+ # Validate the length of a String, Array or any other form attribute which
117
+ # responds to #size. If the value is too short, append the :too_short
118
+ # error to the attribute. If the value is too long append the :too_long
119
+ # error to the attribute.
120
+ #
121
+ # @param attribute_name [Symbol]
122
+ # @option options [Integer, nil] :min (nil)
123
+ # @option options [Integer, nil] :max (nil)
124
+ def validate_length(attribute_name, options = {})
125
+ # TODO: Support :unless_already_invalid => true in more validators.
126
+ return if options.fetch(:unless_already_invalid, false) && attribute_has_errors?(attribute_name)
127
+
128
+ min = options.fetch(:min, nil)
129
+ max = options.fetch(:max, nil)
130
+ value = attributes[attribute_name]
131
+
132
+ return if options[:allow_blank] && value.blank?
133
+
134
+ if value
135
+ length = value.size
136
+ if min && length < min
137
+ append_error(attribute_name, options.fetch(:min_message, nil) || :is_too_short)
138
+ end
139
+ if max && length > max
140
+ append_error(attribute_name, options.fetch(:max_message, nil) || :is_too_long)
141
+ end
142
+ end
143
+ end
144
+
145
+ # Validate the value of the given attribute is included in the list. If
146
+ # the value is not included in the list, append the :not_listed error to
147
+ # the attribute.
148
+ #
149
+ # @param attribute_name [Symbol]
150
+ # @param list [Array]
151
+ def validate_inclusion(attribute_name, list, message = nil)
152
+ value = attributes[attribute_name]
153
+ if value && !list.include?(value)
154
+ append_error(attribute_name, message || :isnt_listed)
155
+ end
156
+ end
157
+
158
+ # Validate the presence of each object in attribute name within list. If the object
159
+ # is not included in the list, append the :not_listed error to the attribute.
160
+ def validate_inclusion_of_each(attribute_name, list, message = nil)
161
+ value = send(attribute_name)
162
+ value && value.each do |obj|
163
+ unless list.include?(obj)
164
+ append_error(attribute_name, message || "#{obj} isn't listed")
165
+ break
166
+ end
167
+ end
168
+ end
169
+
170
+ # Validate the value of the given attribute is not empty.
171
+ # Appends :cant_be_empty error.
172
+ #
173
+ # @param attribute_name [Symbol]
174
+ def validate_any(attribute_name, message = nil)
175
+ value = attributes[attribute_name]
176
+ if value && value.empty?
177
+ append_error(attribute_name, message || :cant_be_empty)
178
+ end
179
+ end
180
+
181
+ # Validate the type of the file sent if included in the list. If it's not,
182
+ # append an :invalid_file error to the attribute.
183
+ #
184
+ # @param attribute_name [Symbol]
185
+ # @param filetypes [Array<String>]
186
+ def validate_filetype(attribute_name, filetypes, message = nil)
187
+ value = send(attribute_name)
188
+ if value && !filetypes.include?(value[:type].to_s.split("/").first)
189
+ append_error(attribute_name, message || :is_invalid)
190
+ end
191
+ end
192
+
193
+ # Validate the range in which the attribute can be. If the value is less
194
+ # than the min a :less_than_min error will be appended. If the value is
195
+ # greater than the max a :greater_than_max error will be appended.
196
+ #
197
+ # @param attribute_name [Symbol]
198
+ # @option options [Integer] :min (nil)
199
+ # The minimum value the attribute can take, if nil, no validation is made.
200
+ # @option options [Integer] :max (nil)
201
+ # The maximum value the attribute can take, if nil, no validation is made.
202
+ def validate_range(attribute_name, options = {})
203
+ value = send(attribute_name)
204
+
205
+ return unless value
206
+
207
+ min = options.fetch(:min, nil)
208
+ max = options.fetch(:max, nil)
209
+ append_error(attribute_name, options.fetch(:min_message, nil) || :less_than_min) if min && value < min
210
+ append_error(attribute_name, options.fetch(:max_message, nil) || :greater_than_max) if max && value > max
211
+ end
212
+
213
+ end
214
+ end
@@ -0,0 +1,3 @@
1
+ module Gourami
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,107 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: gourami
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - TSMMark
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-12-13 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: '1.13'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.13'
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: minitest
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '5.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '5.0'
55
+ description: Create Plain Old Ruby Objects that take attributes, validate them, and
56
+ perform an action.
57
+ email:
58
+ - 9thousand@gmail.com
59
+ executables: []
60
+ extensions: []
61
+ extra_rdoc_files: []
62
+ files:
63
+ - ".gitignore"
64
+ - ".travis.yml"
65
+ - CODE_OF_CONDUCT.md
66
+ - Gemfile
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - bin/console
71
+ - bin/setup
72
+ - gourami.gemspec
73
+ - lib/gourami.rb
74
+ - lib/gourami/attributes.rb
75
+ - lib/gourami/coercer.rb
76
+ - lib/gourami/extensions/resources.rb
77
+ - lib/gourami/form.rb
78
+ - lib/gourami/formatting_constants.rb
79
+ - lib/gourami/required_attribute_error.rb
80
+ - lib/gourami/validation_error.rb
81
+ - lib/gourami/validations.rb
82
+ - lib/gourami/version.rb
83
+ homepage: http://github.com/TSMMark/gourami
84
+ licenses:
85
+ - MIT
86
+ metadata: {}
87
+ post_install_message:
88
+ rdoc_options: []
89
+ require_paths:
90
+ - lib
91
+ required_ruby_version: !ruby/object:Gem::Requirement
92
+ requirements:
93
+ - - ">="
94
+ - !ruby/object:Gem::Version
95
+ version: '0'
96
+ required_rubygems_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: '0'
101
+ requirements: []
102
+ rubyforge_project:
103
+ rubygems_version: 2.4.8
104
+ signing_key:
105
+ specification_version: 4
106
+ summary: Keep your Routes, Controllers and Models thin.
107
+ test_files: []