simple_model_view 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 3fe07953361ca1aeb9f5ee0410173b83d2b9c16cf8c339b083befeac4f7ee337
4
+ data.tar.gz: f1ca40045fb2d9645e6e511c42d4b6a02bb62d91b84d6617cf44f8af49538937
5
+ SHA512:
6
+ metadata.gz: dd6d5d49ea8d0a1c89d5222ccbd9798dd5db43879aff884f067dcb61ec3092016d5fd46c44179c262ecb572dc00177a35e3b235fa98543fd4ab8d658827cde89
7
+ data.tar.gz: ea08a12bf899834e170841f635d1cffa7930cae7b11cdc71e611dbeee6a117c2d7dbf021df58245ea91b5b89accacfdf850f66e59066f725ef7d8c82cb4736d2
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,2 @@
1
+ --color
2
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,130 @@
1
+ # This config aims:
2
+ #
3
+ # - compact, readable and reusable source,
4
+ # - consistent constructions (same things stay the same in different context),
5
+ # - consistent indentation,
6
+ # - avoiding unnecessary lines in diffs
7
+ # - wise usage of Ruby features and expressiveness.
8
+
9
+ require: rubocop-performance
10
+
11
+ AllCops:
12
+ TargetRubyVersion: 2.3
13
+ Exclude:
14
+ - bin/spring
15
+ - db/schema.rb
16
+ - tmp/**/*
17
+ - node_modules/**/*
18
+
19
+ # Disable, till rubocop supports combination of styles.
20
+ # Use one of this styles where appropriate, keep it clean, compact and readable.
21
+ Layout/ArgumentAlignment: {Enabled: false}
22
+
23
+ # Allow bot key & table.
24
+ # https://github.com/rubocop-hq/rubocop/issues/6410
25
+ Layout/HashAlignment: {Enabled: false}
26
+
27
+ # Breaks
28
+ #
29
+ # I18n.t(key,
30
+ # param: val,
31
+ # # ...
32
+ # )
33
+ Layout/ClosingParenthesisIndentation: {Enabled: false}
34
+
35
+ # Allows copy-pasting to repl.
36
+ Layout/DotPosition: {EnforcedStyle: trailing}
37
+
38
+ # Unnecessary, and less readable with small methods.
39
+ Layout/EmptyLineAfterGuardClause: {Enabled: false}
40
+
41
+ # Args alignment is prefered for migrations.
42
+ Layout/ExtraSpacing:
43
+ Exclude:
44
+ - db/migrate/*
45
+
46
+ Layout/FirstArgumentIndentation: {EnforcedStyle: consistent}
47
+ Layout/FirstHashElementIndentation: {EnforcedStyle: consistent}
48
+ Layout/FirstArrayElementIndentation: {EnforcedStyle: consistent}
49
+
50
+ # `new_line` does not work with
51
+ #
52
+ # call(:x, %w[
53
+ # ...
54
+ # ])
55
+ Layout/MultilineMethodCallBraceLayout: {Enabled: false}
56
+ # Same as Layout/ClosingParenthesisIndentation
57
+ Layout/MultilineMethodCallIndentation: {EnforcedStyle: indented}
58
+ Layout/MultilineOperationIndentation: {EnforcedStyle: indented}
59
+
60
+ Layout/SpaceInsideHashLiteralBraces: {EnforcedStyle: no_space}
61
+
62
+ # Keep everything consistent.
63
+ Layout/SpaceBeforeBlockBraces: {EnforcedStyleForEmptyBraces: space}
64
+
65
+ # Offences named scopes and `expect {}.to change {}`.
66
+ Lint/AmbiguousBlockAssociation: {Enabled: false}
67
+
68
+ # Metrics for good perception and expressiveness.
69
+ Metrics/AbcSize:
70
+ Max: 25
71
+ Exclude:
72
+ - db/migrate/*
73
+
74
+ # Other metrics are just enough.
75
+ # This one offences all specs, routes and some initializers.
76
+ Metrics/BlockLength: {Enabled: false}
77
+ Metrics/ClassLength:
78
+ CountComments: false
79
+ Max: 250
80
+ Metrics/CyclomaticComplexity: {Max: 7}
81
+ Metrics/LineLength: {Max: 130}
82
+ Metrics/MethodLength:
83
+ Max: 30
84
+ Exclude:
85
+ - db/migrate/*
86
+ Metrics/ParameterLists: {CountKeywordArgs: false}
87
+
88
+ Naming/VariableNumber: {EnforcedStyle: snake_case}
89
+ Naming/MemoizedInstanceVariableName: {EnforcedStyleForLeadingUnderscores: optional}
90
+ Naming/MethodParameterName: {MinNameLength: 2}
91
+
92
+ Style/Alias: {EnforcedStyle: prefer_alias_method}
93
+
94
+ # Controllers and helpers does not require to be scoped.
95
+ Style/ClassAndModuleChildren:
96
+ Exclude:
97
+ - app/controllers/**/*
98
+ - app/helpers/**/*
99
+
100
+ # Don't require documentation.
101
+ Style/Documentation: {Enabled: false}
102
+
103
+ # Consistent to other definitions.
104
+ Style/EmptyMethod: {EnforcedStyle: expanded}
105
+
106
+ # Does not work with strftime templates and other strings
107
+ # that are not about to be formated with `format`.
108
+ Style/FormatStringToken: {Enabled: false}
109
+
110
+ # Modifiers are less readable sometimes
111
+ Style/IfUnlessModifier: {Enabled: false}
112
+
113
+ Style/Lambda: {EnforcedStyle: literal}
114
+
115
+ Style/MixinUsage:
116
+ Exclude:
117
+ - bin/setup
118
+ - bin/update
119
+
120
+ # `module_function` & `extend self` has different purpose. Use wisely.
121
+ Style/ModuleFunction: {Enabled: false}
122
+
123
+ Style/RescueStandardError: {EnforcedStyle: implicit}
124
+ Style/SignalException: {EnforcedStyle: only_raise}
125
+
126
+ # Does not work well with **options and single args.
127
+ Style/TrailingCommaInArguments: {Enabled: false}
128
+
129
+ Style/TrailingCommaInArrayLiteral: {EnforcedStyleForMultiline: consistent_comma}
130
+ Style/TrailingCommaInHashLiteral: {EnforcedStyleForMultiline: consistent_comma}
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.6.5
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.1
data/CHANGELOG.md ADDED
@@ -0,0 +1,2 @@
1
+ ## 0.1.0
2
+ * First step.
@@ -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 corlinus@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,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in simple_model_view.gemspec
6
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,113 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ simple_model_view (0.1.0)
5
+ actionview (>= 5.0)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ actionpack (6.0.1)
11
+ actionview (= 6.0.1)
12
+ activesupport (= 6.0.1)
13
+ rack (~> 2.0)
14
+ rack-test (>= 0.6.3)
15
+ rails-dom-testing (~> 2.0)
16
+ rails-html-sanitizer (~> 1.0, >= 1.2.0)
17
+ actionview (6.0.1)
18
+ activesupport (= 6.0.1)
19
+ builder (~> 3.1)
20
+ erubi (~> 1.4)
21
+ rails-dom-testing (~> 2.0)
22
+ rails-html-sanitizer (~> 1.1, >= 1.2.0)
23
+ activesupport (6.0.1)
24
+ concurrent-ruby (~> 1.0, >= 1.0.2)
25
+ i18n (>= 0.7, < 2)
26
+ minitest (~> 5.1)
27
+ tzinfo (~> 1.1)
28
+ zeitwerk (~> 2.2)
29
+ ast (2.4.0)
30
+ builder (3.2.3)
31
+ byebug (11.0.1)
32
+ concurrent-ruby (1.1.5)
33
+ crass (1.0.5)
34
+ diff-lcs (1.3)
35
+ erubi (1.9.0)
36
+ i18n (1.7.0)
37
+ concurrent-ruby (~> 1.0)
38
+ jaro_winkler (1.5.4)
39
+ loofah (2.4.0)
40
+ crass (~> 1.0.2)
41
+ nokogiri (>= 1.5.9)
42
+ method_source (0.9.2)
43
+ mini_portile2 (2.4.0)
44
+ minitest (5.13.0)
45
+ nokogiri (1.10.5)
46
+ mini_portile2 (~> 2.4.0)
47
+ parallel (1.19.1)
48
+ parser (2.6.5.0)
49
+ ast (~> 2.4.0)
50
+ rack (2.0.7)
51
+ rack-test (1.1.0)
52
+ rack (>= 1.0, < 3)
53
+ rails-dom-testing (2.0.3)
54
+ activesupport (>= 4.2.0)
55
+ nokogiri (>= 1.6)
56
+ rails-html-sanitizer (1.3.0)
57
+ loofah (~> 2.3)
58
+ railties (6.0.1)
59
+ actionpack (= 6.0.1)
60
+ activesupport (= 6.0.1)
61
+ method_source
62
+ rake (>= 0.8.7)
63
+ thor (>= 0.20.3, < 2.0)
64
+ rainbow (3.0.0)
65
+ rake (10.5.0)
66
+ rspec-core (3.9.0)
67
+ rspec-support (~> 3.9.0)
68
+ rspec-expectations (3.9.0)
69
+ diff-lcs (>= 1.2.0, < 2.0)
70
+ rspec-support (~> 3.9.0)
71
+ rspec-mocks (3.9.0)
72
+ diff-lcs (>= 1.2.0, < 2.0)
73
+ rspec-support (~> 3.9.0)
74
+ rspec-rails (3.9.0)
75
+ actionpack (>= 3.0)
76
+ activesupport (>= 3.0)
77
+ railties (>= 3.0)
78
+ rspec-core (~> 3.9.0)
79
+ rspec-expectations (~> 3.9.0)
80
+ rspec-mocks (~> 3.9.0)
81
+ rspec-support (~> 3.9.0)
82
+ rspec-support (3.9.0)
83
+ rubocop (0.77.0)
84
+ jaro_winkler (~> 1.5.1)
85
+ parallel (~> 1.10)
86
+ parser (>= 2.6)
87
+ rainbow (>= 2.2.2, < 4.0)
88
+ ruby-progressbar (~> 1.7)
89
+ unicode-display_width (>= 1.4.0, < 1.7)
90
+ rubocop-performance (1.5.1)
91
+ rubocop (>= 0.71.0)
92
+ ruby-progressbar (1.10.1)
93
+ thor (0.20.3)
94
+ thread_safe (0.3.6)
95
+ tzinfo (1.2.5)
96
+ thread_safe (~> 0.1)
97
+ unicode-display_width (1.6.0)
98
+ zeitwerk (2.2.1)
99
+
100
+ PLATFORMS
101
+ ruby
102
+
103
+ DEPENDENCIES
104
+ bundler (~> 2.0)
105
+ byebug (~> 11.0.0)
106
+ rake (~> 10.0)
107
+ rspec-rails (~> 3.9)
108
+ rubocop (~> 0.77.0)
109
+ rubocop-performance (~> 1.5.1)
110
+ simple_model_view!
111
+
112
+ BUNDLED WITH
113
+ 2.0.2
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2019 Yuriy Esaulov
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,103 @@
1
+ # SimpleModelView
2
+
3
+ ## Installation
4
+
5
+ Add this line to your application's Gemfile:
6
+
7
+ ```ruby
8
+ gem 'simple_model_view'
9
+ ```
10
+
11
+ And then execute:
12
+
13
+ $ bundle
14
+
15
+ Or install it yourself as:
16
+
17
+ $ gem install simple_model_view
18
+
19
+ ## Usage
20
+
21
+ SimpleModelView provides you two main helpers
22
+
23
+ ### resource_table_for
24
+
25
+ Renders model attributes table using simple helpers.
26
+
27
+ <%= resource_table_for @user do |t| %>
28
+ <%= t.row :id %>
29
+ <%= t.row :name %>
30
+ <% end %>
31
+
32
+ ### collection_table_for
33
+
34
+ <%= collection_table_for @users do |t| %>
35
+ <%= t.column :id %>
36
+ <%= t.column :name %>
37
+ <% end %>
38
+
39
+ #### Common options for `row` and `column`
40
+
41
+ * `title` sets attribute title for table. `human_attribute_name` of String#humanize will be used if `title` is not set.
42
+
43
+ `<%= t.row :name, title: 'Article name' %>`
44
+
45
+ * renders friends array as unorderd list
46
+
47
+ `<%= t.row :friends %>`
48
+
49
+ * `collection: false` option will render attribute as is
50
+
51
+ `<%= t.row :roles, collection: false %>`
52
+
53
+ * `type_specific_class` option will add some useful classes to the wrapper
54
+ * for `numeric` types these are `negative`, `zero`, `positive`
55
+ * for `date` and `datetime` these are `past`, `yesterday`, `today`, `tomorrow`, `future`
56
+ * for `boolean` - `true` and `false`
57
+
58
+ `<%= t.row :account, type_specific_class: true %>`
59
+
60
+ * `custom_class` option will add `child` or `adult` class to the wrapper depends on block result
61
+
62
+ `<%= t.row :age, custom_class: {child: { |x| x < 21 }, adult: { |x| x >= 21 } %>`
63
+
64
+ * `wrapper_html` is a hash of html attributes to be added to wrapper
65
+
66
+ `<%= t.row, wrapper_html: {data: {id: t.object.id}} %>`
67
+
68
+ * `format` will be added to the formatter
69
+
70
+ `string` will be used as format itself
71
+
72
+ `<%= t.row :price, format: '%.2f' %>`
73
+
74
+ `symbol` will be used to find in the locale file
75
+
76
+ `<%= t.row :price, format: '%.2f' %>`
77
+
78
+ ### Options for `row`
79
+
80
+ * `label_html` is a hash of html attributes to be added to label (th tag)
81
+ * `value_html` is a hash of html attributes to be added to value (tr tag)
82
+
83
+ ### Options for `column`
84
+
85
+ * `header_html` is a hash of html attributes to be added to table header (th tag)
86
+
87
+ ## Development
88
+
89
+ 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.
90
+
91
+ 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).
92
+
93
+ ## Contributing
94
+
95
+ Bug reports and pull requests are welcome on GitHub at https://github.com/corlinus/simple_model_view. 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.
96
+
97
+ ## License
98
+
99
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
100
+
101
+ ## Code of Conduct
102
+
103
+ Everyone interacting in the SimpleModelView project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/corlinus/simple_model_view/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'simple_model_view'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ 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,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleModelView
4
+ class ActionViewHelperBuilder
5
+ include SimpleModelView::TemplateHelpers
6
+
7
+ def initialize(template)
8
+ @template = template
9
+ end
10
+
11
+ attr_reader :template
12
+
13
+ def resource_table(model, *args)
14
+ builder = SimpleModelView::ResourceTableBuilder.new template, model, *args
15
+
16
+ template.content_tag :table, class: :table do
17
+ template.content_tag :tbody do
18
+ yield builder
19
+ end
20
+ end
21
+ end
22
+
23
+ def collection_table(collection, *args, &block)
24
+ builder = SimpleModelView::CollectionTableBuilder.new template, collection, *args
25
+
26
+ template.content_tag :table, class: :table do
27
+ block_concat do
28
+ template.content_tag :thead do
29
+ template.content_tag :tr do
30
+ columns_builder = builder.columns_builder
31
+ yield columns_builder
32
+ end
33
+ end
34
+ end
35
+ block_concat do
36
+ template.content_tag :tbody do
37
+ collection.each do |el|
38
+ block_concat do
39
+ template.content_tag :tr do
40
+ row_builder = builder.row_builder_for el
41
+ yield row_builder
42
+ end
43
+ end
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleModelView
4
+ module ActionViewHelpers
5
+ def resource_table_for(resource, *args, &block)
6
+ SimpleModelView::ActionViewHelperBuilder.new(self).resource_table(resource, args, &block)
7
+ end
8
+
9
+ def resource_table(*args, &block)
10
+ resource_table_for resource, *args, &block
11
+ end
12
+
13
+ def collection_table_for(collection, *args, &block)
14
+ SimpleModelView::ActionViewHelperBuilder.new(self).collection_table(collection, *args, &block)
15
+ end
16
+
17
+ def collection_table(*args, &block)
18
+ collection_table_for collection, *args, &block
19
+ end
20
+ end
21
+ end
22
+
23
+ ActiveSupport.on_load(:action_view) do
24
+ include SimpleModelView::ActionViewHelpers
25
+ end
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleModelView
4
+ module BuilderHelpers
5
+ def format(value, type, **options)
6
+ return if value.nil?
7
+
8
+ formatter.new.call value, type, options
9
+ end
10
+
11
+ private
12
+
13
+ def add_type_specific_class(value, type) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
14
+ return if value.nil?
15
+
16
+ case type
17
+ when :boolean
18
+ value.to_s
19
+
20
+ when :date, :time
21
+ if value.today?
22
+ 'today'
23
+ elsif value.past?
24
+ value.since(1.day).today? ? 'past yesterday' : 'past'
25
+ else
26
+ value.ago(1.day).today? ? 'future tomorrow' : 'future'
27
+ end
28
+
29
+ when :integer, :float
30
+ if value.zero?
31
+ 'zero'
32
+ elsif value.negative?
33
+ 'negative'
34
+ else
35
+ 'positive'
36
+ end
37
+ end
38
+ end
39
+
40
+ def add_custom_class(value, classes)
41
+ return if value.nil?
42
+
43
+ classes.select do |_k, v|
44
+ if v.is_a?(Symbol)
45
+ value.public_send(v)
46
+ elsif v.respond_to?(:call)
47
+ v.call(value)
48
+ end
49
+ end.keys.join(' ')
50
+ end
51
+
52
+ def autodetect_value_type(value) # rubocop:disable Metrics/CyclomaticComplexity
53
+ case value
54
+ when Float
55
+ :float
56
+ when Integer
57
+ :integer
58
+ when BigDecimal
59
+ :big_decimal
60
+ when Time, DateTime, ActiveSupport::TimeWithZone
61
+ :time
62
+ when Date
63
+ :date
64
+ when TrueClass, FalseClass
65
+ :boolean
66
+ when String, Symbol
67
+ :string
68
+ else
69
+ :object
70
+ end
71
+ end
72
+
73
+ def prepare_render_data(attr_name:, options:)
74
+ value = object.public_send(attr_name)
75
+
76
+ collection = options[:collection]
77
+ collection = value.class < Enumerable if collection.nil?
78
+
79
+ value_type = :id if attr_name.to_s == 'id'
80
+ value_type ||= options[:as]
81
+ value_type ||= autodetect_value_type(value)
82
+
83
+ wrapper_html = options[:wrapper_html] || {}
84
+ custom_class = options[:custom_class] || {}
85
+
86
+ classes = [*wrapper_html[:class]]
87
+ classes.push(collection ? :collection : value_type)
88
+ classes.push(add_type_specific_class(value, value_type)) if options[:type_specific_class]
89
+ classes.push(add_custom_class(value, custom_class)) unless custom_class.empty?
90
+ classes.compact!
91
+ wrapper_html[:class] = classes
92
+
93
+ {
94
+ value: value,
95
+ value_type: value_type,
96
+ collection: collection,
97
+ wrapper_html: wrapper_html,
98
+ }
99
+ end
100
+
101
+ def render_value(data, **options, &block)
102
+ if data[:collection]
103
+ render_collection data[:value] do |el|
104
+ type = autodetect_value_type(el)
105
+ format_value_or_block el, type, options, &block
106
+ end
107
+ else
108
+ format_value_or_block data[:value], data[:value_type], options, &block
109
+ end
110
+ end
111
+
112
+ def format_value_or_block(value, type, **options, &block)
113
+ return yield value if block
114
+ return blank_span if value.nil?
115
+
116
+ format value, type, **options
117
+ end
118
+
119
+ def render_collection(collection)
120
+ template.content_tag :ul do
121
+ collection.each do |el|
122
+ template.concat(template.content_tag(:li, (yield el)))
123
+ end
124
+ end
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,23 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleModelView
4
+ class CollectionTableBuilder
5
+ include SimpleModelView::TemplateHelpers
6
+ include SimpleModelView::BuilderHelpers
7
+
8
+ def initialize(template, collection, *_args)
9
+ @template = template
10
+ @collection = collection
11
+ end
12
+
13
+ attr_reader :template, :collection
14
+
15
+ def columns_builder
16
+ CollectionTableHeaderBuilder.new template, collection
17
+ end
18
+
19
+ def row_builder_for(resource)
20
+ CollectionTableRowBuilder.new template, resource
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleModelView
4
+ class CollectionTableHeaderBuilder
5
+ include SimpleModelView::TemplateHelpers
6
+
7
+ attr_reader :template, :collection
8
+
9
+ def initialize(template, collection)
10
+ @template = template
11
+ @collection = collection
12
+ end
13
+
14
+ def column(attr_name, *_args, **options)
15
+ title = options[:title]
16
+ title ||= if collection_class
17
+ collection_class.human_attribute_name attr_name
18
+ else
19
+ attr_name.to_s.humanize
20
+ end
21
+ template.content_tag :th, title, options[:header_html] || {}
22
+ end
23
+
24
+ def actions(*_args, **options)
25
+ th_html_attributes = merge_html_attrs default_header_html, options[:header_html].to_h
26
+ template.content_tag :th, options[:title].to_s, **th_html_attributes
27
+ end
28
+
29
+ private
30
+
31
+ def collection_class
32
+ return @collection_class unless @collection_class.nil?
33
+
34
+ @collection_class =
35
+ if defined?(ActiveRecord::Relation) && collection < ActiveRecord::Relation
36
+ collection.new
37
+ else
38
+ false
39
+ end
40
+ end
41
+
42
+ # TODO: gem configuration to be used
43
+ def default_header_html
44
+ {}
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleModelView
4
+ class CollectionTableRowBuilder
5
+ include SimpleModelView::TemplateHelpers
6
+ include SimpleModelView::BuilderHelpers
7
+
8
+ def initialize(template, object, *_args, formatter: SimpleModelView::ValueFormatter)
9
+ @template = template
10
+ @object = object
11
+ @formatter = formatter
12
+ end
13
+
14
+ attr_reader :template, :formatter, :object
15
+
16
+ def column(attr_name, **options, &block)
17
+ render_data = prepare_render_data(attr_name: attr_name, options: options)
18
+
19
+ render_column render_data[:wrapper_html] do
20
+ render_value render_data, options, &block
21
+ end
22
+ end
23
+
24
+ def actions(*_args)
25
+ template.content_tag(:td, nil) do
26
+ yield object if block_given?
27
+ end
28
+ end
29
+
30
+ private
31
+
32
+ def render_column(wrapper_html)
33
+ template.content_tag(:td, nil, **merge_html_attrs(default_wrapper_html, wrapper_html)) do
34
+ yield
35
+ end
36
+ end
37
+
38
+ # TODO: gem configuration to be used
39
+ def default_wrapper_html
40
+ {}
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,9 @@
1
+ en:
2
+ simple_model_view:
3
+ formats:
4
+ boolean:
5
+ "true": 'Yes'
6
+ "false": 'No'
7
+ integer: '%d'
8
+ float: '%.5f'
9
+ empty: 'empty'
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'rails/railtie'
4
+
5
+ module SimpleModelView
6
+ class Railtie < Rails::Railtie
7
+ config.eager_load_namespaces << SimpleModelView
8
+ end
9
+ end
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleModelView
4
+ class ResourceTableBuilder
5
+ include SimpleModelView::TemplateHelpers
6
+ include SimpleModelView::BuilderHelpers
7
+
8
+ def initialize(template, object, *_args, formatter: SimpleModelView::ValueFormatter)
9
+ @template = template
10
+ @object = object
11
+ @formatter = formatter
12
+ end
13
+
14
+ attr_reader :formatter, :object
15
+
16
+ # Renders row for given +attr_name+.
17
+ #
18
+ # === Arguments
19
+ #
20
+ # * +attr_name+ - Attribute to be rendered as a +Symbol+ or +String+.
21
+ # * +title:+ - +String+ to use as attribute name in table.
22
+ # Using +human_attribute_name+ or if not given.
23
+ # * +as:+ - Force attribute value type _(:boolean, :date, :time, :integer, :float, etc...)_.
24
+ # * +collection:+ - If +true+ tryes to interpret value as a iterateble collection.
25
+ # * +type_specific_class:+ - adds type specific classes to the wrapper <tr> tag.
26
+ # For numeric it would be `negative`, `zero`, `positieve`;
27
+ # For date and time it would be `past`, `future`, `yesterday`, etc;
28
+ # See Examples for more details.
29
+ # * +custom_class:+ - +Hash+ with values as +Symbol+ or any +callable object+. symbol will be
30
+ # sent to the value as a method. Proc will be called and passed a value as an argument. If
31
+ # method or block retuns not +false+ or +nil+ hash key will be added as a class to the
32
+ # wrapper <tr> tag.
33
+ # * +wrapper_html:+ - html attributes to add to wrapper <tr> tag.
34
+ # * +label_html:+ - html attributes to add to attribute title <th> tag.
35
+ # * +value_html:+ - html attributes to add to attribute value <td> tag.
36
+ # * +**options+ - all other named arguments will be passed to the formatter.
37
+ # * &block - if block given it will render inside value cell.
38
+ #
39
+ # === Examples
40
+ #
41
+ # TODO:
42
+ #
43
+ def row(attr_name, title: nil, **options, &block)
44
+ title ||= if object.class.respond_to?(:human_attribute_name)
45
+ object.class.human_attribute_name attr_name
46
+ else
47
+ attr_name.to_s.humanize
48
+ end
49
+
50
+ render_data = prepare_render_data(attr_name: attr_name, options: options)
51
+
52
+ label_html = options[:label_html] || {}
53
+ value_html = options[:value_html] || {}
54
+
55
+ render_row title, render_data[:wrapper_html], label_html, value_html do
56
+ render_value render_data, options, &block
57
+ end
58
+ end
59
+
60
+ private
61
+
62
+ attr_reader :template
63
+
64
+ def render_row(title, wrapper_html, label_html, value_html)
65
+ template.content_tag(:tr, **merge_html_attrs(default_wrapper_html, wrapper_html)) do
66
+ template.concat template.content_tag(:th, title,
67
+ **merge_html_attrs(default_label_html, label_html))
68
+
69
+ block_concat do
70
+ template.content_tag :td, yield, **merge_html_attrs(default_value_html, value_html)
71
+ end
72
+ end
73
+ end
74
+
75
+ # TODO: gem configuration to be used
76
+ def default_wrapper_html
77
+ {}
78
+ end
79
+
80
+ def default_label_html
81
+ {}
82
+ end
83
+
84
+ def default_value_html
85
+ {}
86
+ end
87
+ end
88
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleModelView
4
+ module TemplateHelpers
5
+ def block_concat
6
+ template.concat yield
7
+ end
8
+
9
+ def blank_span
10
+ template.content_tag :span, 'empty', class: :empty
11
+ end
12
+
13
+ def merge_html_attrs(default, input)
14
+ result = default.transform_keys(&:to_sym)
15
+ input = input.transform_keys(&:to_sym)
16
+
17
+ if result[:data].is_a?(Hash) && input[:data].is_a?(Hash)
18
+ input[:data] = result[:data].merge(input[:data])
19
+ end
20
+
21
+ if result[:class] && input[:class]
22
+ input[:class] = [*default[:class], *input[:class]]
23
+ end
24
+
25
+ result.merge! input
26
+ result.compact!
27
+ result
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,77 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleModelView
4
+ class ValueFormatter
5
+ attr_reader :value, :options
6
+
7
+ def call(value, type, options)
8
+ @value = value
9
+ @options = options
10
+ public_send "format_#{type}"
11
+ end
12
+
13
+ def format_id
14
+ value.to_s
15
+ end
16
+
17
+ def format_boolean
18
+ I18n.t "simple_model_view.formats.boolean.#{value}"
19
+ end
20
+
21
+ def format_date
22
+ case options[:format]
23
+ when Symbol
24
+ I18n.l value, format: options[:format]
25
+
26
+ when String
27
+ value.strftime options[:format]
28
+
29
+ else
30
+ I18n.l value
31
+ end
32
+ end
33
+
34
+ alias_method :format_time, :format_date
35
+
36
+ def format_integer
37
+ value_format 'integer'
38
+ end
39
+
40
+ def format_float
41
+ value_format 'float'
42
+ end
43
+
44
+ def format_html
45
+ raise NotImplementedError, '`html` is not implemented yet'
46
+ end
47
+
48
+ def format_md
49
+ raise NotImplementedError, '`md` is not implemented yet'
50
+ end
51
+
52
+ def format_inspect
53
+ value.inspect
54
+ end
55
+
56
+ def format_object
57
+ value.to_s
58
+ end
59
+
60
+ def format_string
61
+ value
62
+ end
63
+
64
+ private
65
+
66
+ def value_format(type)
67
+ format_string = fetch_format_string options[:format], "simple_model_view.formats.#{type}"
68
+ format_string ? format_string % value : value.to_s
69
+ end
70
+
71
+ def fetch_format_string(format, path)
72
+ return unless format
73
+ return I18n.t(format, scope: path) if format.is_a?(Symbol)
74
+ format.to_s
75
+ end
76
+ end
77
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SimpleModelView
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'action_view'
4
+ require 'simple_model_view/version'
5
+ require 'simple_model_view/action_view_helpers'
6
+
7
+ module SimpleModelView
8
+ extend ActiveSupport::Autoload
9
+
10
+ eager_autoload do
11
+ autoload :ActionViewHelperBuilder
12
+ autoload :TemplateHelpers
13
+ autoload :ValueFormatter
14
+ autoload :BuilderHelpers
15
+ autoload :ResourceTableBuilder
16
+ autoload :CollectionTableHeaderBuilder
17
+ autoload :CollectionTableRowBuilder
18
+ autoload :CollectionTableBuilder
19
+ end
20
+ end
21
+
22
+ require 'simple_model_view/railtie' if defined?(Rails)
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ lib = File.expand_path('lib', __dir__)
4
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
5
+ require 'simple_model_view/version'
6
+
7
+ Gem::Specification.new do |spec|
8
+ spec.name = 'simple_model_view'
9
+ spec.version = SimpleModelView::VERSION
10
+ spec.authors = ['Yuriy Esaulov']
11
+ spec.email = ['corlinus@gmail.com']
12
+
13
+ spec.summary = 'Simple views for AR model attributes tables and collection of AR models.'
14
+ spec.description = spec.summary
15
+ spec.homepage = 'https://github.com/corlinus/simple_model_view'
16
+ spec.license = 'MIT'
17
+
18
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
19
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
20
+ if spec.respond_to?(:metadata)
21
+ spec.metadata['homepage_uri'] = spec.homepage
22
+ spec.metadata['source_code_uri'] = spec.homepage
23
+ spec.metadata['changelog_uri'] = "#{spec.homepage}/CHANGELOG.md"
24
+ else
25
+ raise 'RubyGems 2.0 or newer is required to protect against ' \
26
+ 'public gem pushes.'
27
+ end
28
+
29
+ # Specify which files should be added to the gem when it is released.
30
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
31
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
32
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
33
+ end
34
+ spec.require_paths = ['lib']
35
+
36
+ spec.required_ruby_version = '>= 2.3.0'
37
+
38
+ spec.add_dependency('actionview', '>= 5.0')
39
+
40
+ spec.add_development_dependency 'bundler', '~> 2.0'
41
+ spec.add_development_dependency 'byebug', '~> 11.0.0'
42
+ spec.add_development_dependency 'rake', '~> 10.0'
43
+ spec.add_development_dependency 'rspec-rails', '~> 3.9'
44
+ spec.add_development_dependency 'rubocop', '~> 0.77.0'
45
+ spec.add_development_dependency 'rubocop-performance', '~> 1.5.1'
46
+ end
metadata ADDED
@@ -0,0 +1,172 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: simple_model_view
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Yuriy Esaulov
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2019-12-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: actionview
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '5.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '5.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: byebug
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: 11.0.0
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: 11.0.0
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec-rails
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.9'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.9'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rubocop
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: 0.77.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.77.0
97
+ - !ruby/object:Gem::Dependency
98
+ name: rubocop-performance
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: 1.5.1
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: 1.5.1
111
+ description: Simple views for AR model attributes tables and collection of AR models.
112
+ email:
113
+ - corlinus@gmail.com
114
+ executables: []
115
+ extensions: []
116
+ extra_rdoc_files: []
117
+ files:
118
+ - ".gitignore"
119
+ - ".rspec"
120
+ - ".rubocop.yml"
121
+ - ".ruby-version"
122
+ - ".travis.yml"
123
+ - CHANGELOG.md
124
+ - CODE_OF_CONDUCT.md
125
+ - Gemfile
126
+ - Gemfile.lock
127
+ - LICENSE.txt
128
+ - README.md
129
+ - Rakefile
130
+ - bin/console
131
+ - bin/setup
132
+ - lib/simple_model_view.rb
133
+ - lib/simple_model_view/action_view_helper_builder.rb
134
+ - lib/simple_model_view/action_view_helpers.rb
135
+ - lib/simple_model_view/builder_helpers.rb
136
+ - lib/simple_model_view/collection_table_builder.rb
137
+ - lib/simple_model_view/collection_table_header_builder.rb
138
+ - lib/simple_model_view/collection_table_row_builder.rb
139
+ - lib/simple_model_view/locales/simple_model_view.en.yml
140
+ - lib/simple_model_view/railtie.rb
141
+ - lib/simple_model_view/resource_table_builder.rb
142
+ - lib/simple_model_view/template_helpers.rb
143
+ - lib/simple_model_view/value_formatter.rb
144
+ - lib/simple_model_view/version.rb
145
+ - simple_model_view.gemspec
146
+ homepage: https://github.com/corlinus/simple_model_view
147
+ licenses:
148
+ - MIT
149
+ metadata:
150
+ homepage_uri: https://github.com/corlinus/simple_model_view
151
+ source_code_uri: https://github.com/corlinus/simple_model_view
152
+ changelog_uri: https://github.com/corlinus/simple_model_view/CHANGELOG.md
153
+ post_install_message:
154
+ rdoc_options: []
155
+ require_paths:
156
+ - lib
157
+ required_ruby_version: !ruby/object:Gem::Requirement
158
+ requirements:
159
+ - - ">="
160
+ - !ruby/object:Gem::Version
161
+ version: 2.3.0
162
+ required_rubygems_version: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: '0'
167
+ requirements: []
168
+ rubygems_version: 3.0.3
169
+ signing_key:
170
+ specification_version: 4
171
+ summary: Simple views for AR model attributes tables and collection of AR models.
172
+ test_files: []