action_presenter-base 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: bf5f1b60b3e4ea0d5b396b1352b2849df8da8dbe
4
+ data.tar.gz: 946f72d1e2381a69e848702ea710009330ad3e60
5
+ SHA512:
6
+ metadata.gz: 0b6d536851c47abc7ac4d36033da0e0a3c36b4ee3922f4a02b94698bf2f37ea003b3b391fb55e8e417bc9fda4139d2581b90fbfa70e567e96652857f21f67246
7
+ data.tar.gz: 97ca48e5ed142a85f3a7ea85c6394fcc9f8e43ffde524f98823803d5a353e2779dd5ce3aeb74abaaf408fa59c0f2e3ffd2c25a1660fbe243373a98d0b3af0cd5
@@ -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.4.1
5
+ before_install: gem install bundler -v 1.15.1
@@ -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 griffithchaffee@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 action_presenter-base.gemspec
4
+ gemspec
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Griffith Chaffee
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,43 @@
1
+ # ActionView::Presenter
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/action_view/presenter`. 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 'action_presenter-base'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install action_presenter-base
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 test` 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]/action_presenter-base. 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](http://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the ActionView::Presenter project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/action_presenter-base/blob/master/CODE_OF_CONDUCT.md).
@@ -0,0 +1,10 @@
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["test/**/*_test.rb"]
8
+ end
9
+
10
+ task :default => :test
@@ -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 "action_presenter/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "action_presenter-base"
8
+ spec.version = ActionPresenter::VERSION
9
+ spec.authors = ["Griffith Chaffee"]
10
+ spec.email = ["griffithchaffee@gmail.com"]
11
+
12
+ spec.summary = %q{Provides presenter logic to views.}
13
+ spec.description = %q{Provides presenter logic to views.}
14
+ spec.homepage = "https://github.com/griffithchaffee/action_presenter-base"
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
+
21
+ spec.require_paths = ["lib"]
22
+
23
+ spec.add_development_dependency "activesupport", "~> 5.1"
24
+ spec.add_development_dependency "actionview", "~> 5.1"
25
+ spec.add_development_dependency "bundler", "~> 1.15"
26
+ spec.add_development_dependency "minitest", "~> 5.0"
27
+ end
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "action_presenter/base"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,139 @@
1
+ module ActionPresenter
2
+ class Base
3
+ # inheritance tracking
4
+ PRESENTER_CLASSES = []
5
+
6
+ def self.inherited(new_presenter_class)
7
+ PRESENTER_CLASSES << new_presenter_class
8
+ super
9
+ end
10
+
11
+ # core methods
12
+ def initialize
13
+ end
14
+
15
+ PRESENTER_ATTRIBUTES = %i[ content record ]
16
+
17
+ attr_accessor :record, :view
18
+
19
+ def set(options)
20
+ options.each { |method, value| send "#{method}=", value }
21
+ self
22
+ end
23
+
24
+ def presenter_options
25
+ self.class.presenter_options.dup
26
+ end
27
+
28
+ def extract(key, *hashes)
29
+ hashes.compact.map do |hash|
30
+ begin
31
+ hash.delete(key.to_sym) || hash.delete(key.to_s)
32
+ rescue StandardError => error
33
+ raise ArgumentError, "#{error.class} while trying to extract key #{key.inspect} from #{hash.inspect}: #{error.message}"
34
+ end
35
+ end.compact.first
36
+ end
37
+
38
+ def extract_html(*hashes)
39
+ html_attributes = {}
40
+ add_classes = []
41
+ remove_classes = []
42
+ merge_data = {}
43
+ reverse_merge_data = {}
44
+ hashes.each do |hash|
45
+ next if hash.blank?
46
+ # custom class attributes
47
+ add_class = extract(:add_class, hash)
48
+ add_classes << add_class if add_class.present?
49
+ remove_class = extract(:remove_class, hash)
50
+ remove_classes << remove_class if remove_class.present?
51
+ # custom data attributes
52
+ merging_data = extract(:merge_data, hash)
53
+ merge_data.merge!(merging_data.to_h.symbolize_keys) if merging_data.present?
54
+ reverse_merging_data = extract(:reverse_merge_data, hash)
55
+ reverse_merge_data.merge!(reverse_merging_data.to_h.symbolize_keys) if reverse_merging_data.present?
56
+ # rest
57
+ html_attributes.reverse_merge!(hash.symbolize_keys)
58
+ end
59
+ # custom class attributes
60
+ if add_classes.present? || remove_classes.present?
61
+ classes_to_a = -> (value) do
62
+ case value
63
+ when Symbol then classes_to_a.call(send(value))
64
+ when Array then value.map { |v| classes_to_a.call(v) }
65
+ else value.to_s.split(/\s/)
66
+ end.flatten
67
+ end
68
+ classes = classes_to_a.call(html_attributes[:class])
69
+ classes += classes_to_a.call(add_classes)
70
+ classes -= classes_to_a.call(remove_classes)
71
+ # reverse so classes appear to append in order
72
+ html_attributes[:class] = classes.uniq.join(" ").presence
73
+ end
74
+ # custom data attributes
75
+ if merge_data.present? || reverse_merge_data.present?
76
+ html_attributes[:data] ||= {}
77
+ html_attributes[:data].merge!(merge_data) if merge_data.present?
78
+ html_attributes[:data].reverse_merge!(reverse_merge_data) if reverse_merge_data.present?
79
+ end
80
+ html_attributes.select do |html_attribute, value|
81
+ !html_attribute.in?(PRESENTER_ATTRIBUTES)
82
+ end
83
+ end
84
+
85
+ def extract_content(*hashes, &content_block)
86
+ content = extract(:content, *hashes)
87
+ # block has highest precedence
88
+ content = view.capture(&content_block) if content_block.is_a?(Proc)
89
+ content = content.to_s if content.is_a?(Numeric)
90
+ # check for escaped HTML
91
+ if presenter_options.verify_content && !content.is_a?(ActiveSupport::SafeBuffer)
92
+ if content =~ /<[a-zA-Z]+( |>)/ || content =~ /&nbsp/
93
+ warning_message = "Escaped HTML in #{self.class} content: #{content}"
94
+ if Rails.env.production?
95
+ Rails.logger.warn { warning_message }
96
+ else
97
+ raise ArgumentError, warning_message
98
+ end
99
+ end
100
+ end
101
+ content
102
+ end
103
+
104
+ def extract_content_block(*hashes, &content_block)
105
+ content_block.is_a?(Proc) ? content_block : proc { extract_content(*hashes) }
106
+ end
107
+
108
+ def extract_record(*hashes)
109
+ extract(:record, *hashes, record: record)
110
+ end
111
+
112
+ def extract_query_params(*hashes)
113
+ extract(:query_params, *hashes, query_params: {})
114
+ end
115
+
116
+ class << self
117
+ def define_extension(base_method, new_method, *extension_params)
118
+ define_method(new_method) do |*params, &content_block|
119
+ send(base_method, *params, *extension_params.deep_dup, &content_block)
120
+ end
121
+ end
122
+
123
+ def presenter_options
124
+ @presenter_options ||= ActiveSupport::OrderedOptions.new.merge(
125
+ verify_content: true,
126
+ presents: name.underscore.remove(/_presenter\z/).singularize.to_sym,
127
+ )
128
+ end
129
+ end
130
+ end
131
+ end
132
+
133
+ require "action_presenter/version"
134
+ require "action_presenter/ruby/string"
135
+ require "action_presenter/ruby/hash"
136
+ require "action_presenter/base/html"
137
+ require "action_presenter/base/form"
138
+ require "action_presenter/base/bootstrap"
139
+ require "action_presenter/railtie" if defined?(Rails)
@@ -0,0 +1,92 @@
1
+ module ActionPresenter
2
+ class Base
3
+ BOOTSTRAP_SIZES = %w[ xs sm md lg ]
4
+ def self.generate_bootstrap_presenter_methods!
5
+ ["", "offset"].each do |namespace|
6
+ define_method("col_#{namespace}_class".squeeze("_")) do |*hashes, &content_block|
7
+ classes = []
8
+ BOOTSTRAP_SIZES.each do |col_size|
9
+ col_width = extract("col_#{col_size}", *hashes).to_i.nonzero?
10
+ if col_width
11
+ col_width += 1 if extract("#{col_size}_expand", *hashes) == true && col_width < 11
12
+ col_width -= 1 if extract("#{col_size}_compact", *hashes) == true && col_width > 2
13
+ raise ArgumentError, "col_width must be between 1 and 12" if !col_width.between?(1,12)
14
+ # col-sm-3
15
+ classes << "col-#{col_size}-#{namespace}-#{col_width}".squeeze("-")
16
+ end
17
+ end
18
+ [extract_html(*hashes)[:class], *classes].join(" ")
19
+ end
20
+ end
21
+
22
+ define_method(:col_div) do |*hashes, &content_block|
23
+ classes = []
24
+ BOOTSTRAP_SIZES.each do |col_size|
25
+ col_width = extract("col_#{col_size}", *hashes).to_i.nonzero?
26
+ col_offset_width = extract("col_#{col_size}_offset", *hashes).to_i.nonzero?
27
+ if col_width
28
+ col_width += 1 if extract("#{col_size}_expand", *hashes) == true && col_width < 11
29
+ col_width -= 1 if extract("#{col_size}_compact", *hashes) == true && col_width > 2
30
+ classes << col_class("col_#{col_size}" => col_width)
31
+ end
32
+ if col_offset_width
33
+ col_offset_width += 1 if extract("#{col_size}_offset_expand", *hashes) == true && col_offset_width < 11
34
+ col_offset_width -= 1 if extract("#{col_size}_offset_compact", *hashes) == true && col_offset_width > 2
35
+ raise ArgumentError, "col_width must be between 1 and 12" if !col_offset_width.between?(1,12)
36
+ classes << col_offset_class("col_#{col_size}" => col_offset_width)
37
+ end
38
+ end
39
+ div_tag(*hashes, add_class: classes.join(" "), &content_block)
40
+ end
41
+
42
+ define_method(:check_box_div_label) do |*hashes, &content_block|
43
+ content = extract_content(*hashes, &content_block)
44
+ check_box_div(*hashes) { label_tag(content: content) }
45
+ end
46
+
47
+ define_method(:label_span) do |label, *hashes, &content_block|
48
+ span_tag(*hashes, add_class: "label label-#{label}", &content_block)
49
+ end
50
+
51
+ define_method(:alert_div) do |alert, *hashes, &content_block|
52
+ div_tag(*hashes, class: "alert alert-#{alert} alert-dismissible", role: "alert", &content_block)
53
+ end
54
+
55
+ define_method(:dismiss_button) do |target, *hashes, &content_block|
56
+ button_tag(*hashes, "aria-label" => "Dismiss", data: { dismiss: target.to_s }, &content_block)
57
+ end
58
+
59
+ define_method(:dropdown_toggle_btn) do |*hashes, &content_block|
60
+ btn = extract(:btn, *hashes, btn: "default")
61
+ button_tag(*hashes, class: "btn btn-#{btn} dropdown-toggle", data: { toggle: "dropdown" }, &content_block)
62
+ end
63
+
64
+ define_method(:glyphicon) do |glyphicon, *hashes, &content_block|
65
+ span_tag(*hashes, add_class: "glyphicon glyphicon-#{glyphicon}", &content_block)
66
+ end
67
+
68
+ # override core classes
69
+ {
70
+ core_label_class: -> { "control-label" },
71
+ core_select_class: -> { "form-control" },
72
+ core_field_class: -> { "form-control" },
73
+ core_text_area_class: -> { "form-control" },
74
+ }.each do |method, block|
75
+ define_method(method, &block)
76
+ end
77
+
78
+ # div
79
+ define_extension(:div_tag, :row_div, class: "row")
80
+ define_extension(:div_tag, :form_group_div, class: "form-group")
81
+ define_extension(:div_tag, :dropdown_div, class: "dropdown")
82
+ define_extension(:div_tag, :check_box_div, class: "checkbox")
83
+ # span
84
+ define_extension(:span_tag, :caret_span, class: "caret")
85
+ # ul
86
+ define_extension(:ul_tag, :dropdown_menu_ul, class: "dropdown-menu", role: "menu")
87
+ # label
88
+ define_extension(:label_tag, :radio_label, class: "radio")
89
+ define_extension(:label_tag, :check_box_label, class: "checkbox")
90
+ end
91
+ end
92
+ end
@@ -0,0 +1,89 @@
1
+ module ActionPresenter
2
+ class Base
3
+ attr_reader :form_builder
4
+
5
+ def form_tag(path, *hashes, &content_block)
6
+ view.form_tag(path, extract_html(*hashes)) do |form_builder|
7
+ self.form_builder = form_builder
8
+ yield(form_builder)
9
+ end
10
+ end
11
+
12
+ def form_for(*hashes, &content_block)
13
+ record = extract_record(*hashes)
14
+ view.form_for(record, extract_html(*hashes)) do |form_builder|
15
+ self.form_builder = form_builder
16
+ yield(form_builder)
17
+ end
18
+ end
19
+
20
+ def form_builder=(new_form_builder)
21
+ @form_builder = new_form_builder
22
+ self.record = form_builder.try(:object)
23
+ @form_builder
24
+ end
25
+
26
+ # form elements
27
+ def label(name, *hashes, &content_block)
28
+ default_html = { class: label_class }
29
+ form_builder.label(name, extract_html(*hashes, default_html), &extract_content_block(*hashes, &content_block))
30
+ end
31
+
32
+ def text_field(name, *hashes, &content_block)
33
+ default_html = { class: text_field_class, value: extract_content(*hashes, &content_block) }.compact
34
+ form_builder.text_field(name, extract_html(*hashes, default_html))
35
+ end
36
+
37
+ def hidden_field(name, *hashes, &content_block)
38
+ default_html = { value: extract_content(*hashes, &content_block) }.compact
39
+ form_builder.hidden_field(name, extract_html(*hashes, default_html))
40
+ end
41
+
42
+ def text_area(name, *hashes, &content_block)
43
+ default_html = { class: text_area_class, value: extract_content(*hashes, &content_block) }.compact
44
+ form_builder.text_area(name, extract_html(*hashes, default_html))
45
+ end
46
+
47
+ def select(name, *hashes, &content_block)
48
+ default_html = { class: select_class }
49
+ content = extract_content(*hashes, &content_block) || {}
50
+ select_options = %i[ include_blank prompt ].map { |key| [key, extract(key, *hashes)] }.to_h
51
+ form_builder.select(name, content, select_options, extract_html(*hashes, default_html))
52
+ end
53
+
54
+ def date_select(name, *hashes)
55
+ default_html = { class: date_select_class }
56
+ hashes << { order: %i[ month day year ] }
57
+ select_options = {}
58
+ %i[
59
+ include_blank prompt
60
+ order default start_year end_year add_month_numbers use_short_month
61
+ ].each { |key| select_options[key] = extract(key, *hashes) }
62
+ form_builder.date_select(name, select_options.compact, extract_html(*hashes, default_html))
63
+ end
64
+
65
+ def datetime_select(name, *hashes)
66
+ default_html = { class: datetime_select_class }
67
+ hashes << { order: %i[ month day year ], ampm: true }
68
+ select_options = {}
69
+ %i[
70
+ include_blank prompt
71
+ ampm order default start_year end_year
72
+ ].each { |key| select_options[key] = extract(key, *hashes) }
73
+ form_builder.datetime_select(name, select_options, extract_html(*hashes, class: datetime_select_class))
74
+ end
75
+
76
+ def check_box(name, *hashes)
77
+ default_html = { class: check_box_class }
78
+ checked_value = extract(:checked_value, *hashes, checked_value: "true")
79
+ unchecked_value = extract(:unchecked_value, *hashes, unchecked_value: "false")
80
+ form_builder.check_box(name, extract_html(*hashes, default_html), checked_value, unchecked_value)
81
+ end
82
+
83
+ def radio_button(name, *hashes, &content_block)
84
+ default_html = { class: radio_button_class }
85
+ content = extract_content(*hashes, &content_block).to_s
86
+ form_builder.radio_button(name, content, extract_html(*hashes, default_html))
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,149 @@
1
+ module ActionPresenter
2
+ class Base
3
+
4
+ def html_tag(tag, *hashes, &content_block)
5
+ view.content_tag(tag, extract_html(*hashes), &extract_content_block(*hashes, &content_block))
6
+ end
7
+
8
+ def inline_html_tag(tag, *hashes, &content_block)
9
+ view.tag(tag, extract_html(*hashes), &extract_content_block(*hashes, &content_block))
10
+ end
11
+
12
+ # html block tags
13
+ %w[
14
+ body iframe
15
+ div span p a label pre
16
+ legend h1 h2 h3 h4 h5 h6
17
+ ol ul li dl dd dt
18
+ table tbody th td tr
19
+ b strong i em small abbr
20
+ ].each do |tag|
21
+ define_method("#{tag}_tag") do |*hashes, &content_block|
22
+ html_tag(tag, *hashes, &content_block)
23
+ end
24
+ end
25
+
26
+ # inline html tags
27
+ %w[ br hr input img meta ].each do |tag|
28
+ define_method("#{tag}_tag") do |*hashes, &content_block|
29
+ inline_html_tag(tag, *hashes, &content_block)
30
+ end
31
+ end
32
+
33
+ def button_tag(*hashes, &content_block)
34
+ default_html = { type: "button" }
35
+ html_tag(:button, *hashes, default_html, &content_block)
36
+ end
37
+
38
+ def submit_tag(*hashes, &content_block)
39
+ view.submit_tag(extract_content(*hashes, content: "Submit", &content_block), extract_html(*hashes))
40
+ end
41
+
42
+ def method_field(*hashes, &content_block)
43
+ hidden_field_tag("_method", *hashes, id: nil, value: "post", &content_block)
44
+ end
45
+
46
+ def image_tag(name, *hashes, &content_block)
47
+ view.image_tag(name, extract_html(*hashes), &extract_content_block(*hashes, &content_block))
48
+ end
49
+
50
+ def link_to(link, *hashes, &content_block)
51
+ view.link_to(link, extract_html(*hashes), &extract_content_block(*hashes, &content_block))
52
+ end
53
+
54
+ # form elements
55
+ def select_tag(name, *hashes, &content_block)
56
+ default_html = { id: name.to_s.slugify_html, name: name, class: select_class }
57
+ content = extract_content(*hashes, &content_block)
58
+ if !content.is_a?(String)
59
+ content = view.options_for_select(content, extract(:selected, *hashes, selected: view.params.to_unsafe_h.dig_html(name)))
60
+ end
61
+ view.select_tag(name, content, extract_html(*hashes, default_html))
62
+ end
63
+
64
+ def text_field_tag(name, *hashes, &content_block)
65
+ default_html = { id: name.to_s.slugify_html, name: name, class: text_field_class }
66
+ content = extract_content(*hashes, content: view.params.to_unsafe_h.dig_html(name), &content_block)
67
+ view.text_field_tag(name, content, extract_html(*hashes, default_html))
68
+ end
69
+
70
+ def file_field_tag(name, *hashes, &content_block)
71
+ default_html = { id: name.to_s.slugify_html, name: name, class: file_field_class }
72
+ view.file_field_tag(name, extract_html(*hashes, default_html))
73
+ end
74
+
75
+ def hidden_field_tag(name, *hashes, &content_block)
76
+ default_html = { id: name.to_s.slugify_html, name: name }
77
+ content = extract_content(*hashes, content: view.params.to_unsafe_h.dig_html(name), &content_block)
78
+ view.hidden_field_tag(name, content, extract_html(*hashes, default_html))
79
+ end
80
+
81
+ def text_area_tag(name, *hashes, &content_block)
82
+ default_html = { id: name.to_s.slugify_html, name: name, class: text_area_class }
83
+ content = extract_content(*hashes, content: view.params.to_unsafe_h.dig_html(name), &content_block)
84
+ view.text_area_tag(name, content, extract_html(*hashes, default_html))
85
+ end
86
+
87
+ def label_for(name, *hashes, &content_block)
88
+ default_html = { class: label_for_class }
89
+ view.label_tag(name, extract_html(*hashes, default_html), &extract_content_block(*hashes, &content_block))
90
+ end
91
+
92
+ def check_box_tag(name, *hashes, &content_block)
93
+ default_html = { id: name.to_s.slugify_html, name: name, class: check_box_class }
94
+ checked_value = extract_content(*hashes, content: "true").presence
95
+ unchecked_value = extract(:unchecked_value, *hashes).presence
96
+ checked = extract(:checked, *hashes, checked: view.params.to_unsafe_h.dig_html(name).presence == checked_value).present?
97
+ check_box_html = extract_html(*hashes, default_html)
98
+ content = "".html_safe
99
+ if unchecked_value.present?
100
+ content += view.check_box_tag(nil, unchecked_value, true, default_html.merge(id: nil, class: nil, style: "display: none;"))
101
+ end
102
+ content + view.check_box_tag(nil, checked_value, checked, check_box_html)
103
+ end
104
+
105
+ def radio_button_tag(name, *hashes, &content_block)
106
+ default_html = { id: name.to_s.slugify_html, name: name, class: radio_button_class }
107
+ content = extract_content(*hashes, &content_block).presence
108
+ active_content = view.params.to_unsafe_h.dig_html(name).presence
109
+ checked = extract(:checked, *hashes)
110
+ checked = checked.in?([true, false]) ? checked : active_content == content
111
+ view.radio_button_tag(nil, content, checked, extract_html(*hashes, default_html))
112
+ end
113
+
114
+ # html classes
115
+ {
116
+ # core
117
+ core_label_class: -> { "" },
118
+ core_select_class: -> { "" },
119
+ core_field_class: -> { "" },
120
+ core_text_area_class: -> { "" },
121
+ core_check_box_class: -> { "" },
122
+ core_radio_button_class: -> { "" },
123
+ # labels
124
+ label_class: -> { core_label_class },
125
+ label_for_class: -> { core_label_class },
126
+ # selects
127
+ select_class: -> { core_select_class },
128
+ date_select_class: -> { core_select_class },
129
+ datetime_select_class: -> { core_select_class },
130
+ # fields
131
+ text_field_class: -> { core_field_class },
132
+ file_field_class: -> { core_field_class },
133
+ # text_area
134
+ text_area_class: -> { core_text_area_class },
135
+ # check_box
136
+ check_box_class: -> { core_check_box_class },
137
+ # radio_button
138
+ radio_button_class: -> { core_radio_button_class },
139
+ }.each do |method, block|
140
+ define_method(method, &block)
141
+ end
142
+
143
+ # element extensions
144
+ define_extension(:script_tag, :javascript_script_tag, type: "text/javascript")
145
+ define_extension(:style_tag, :css_style_tag, type: "text/css")
146
+ define_extension(:link_to, :tab_link, target: "_blank")
147
+
148
+ end
149
+ end
@@ -0,0 +1,6 @@
1
+ module ActionPresenter
2
+ class Railtie < Rails::Railtie
3
+ require "action_presenter/railtie/action_controller"
4
+ require "action_presenter/railtie/action_view"
5
+ end
6
+ end
@@ -0,0 +1,19 @@
1
+ module ActionPresenter
2
+ ActiveSupport.on_load(:action_controller) do
3
+ ::ActionController::Base.class_eval do
4
+ def presenter_options
5
+ @presenter_options ||= self.class.presenter_options.dup
6
+ end
7
+
8
+ class << self
9
+ def presenter_options
10
+ presenter_name = controller_name.gsub(/\W/, "_").underscore
11
+ @presenter_options ||= ActiveSupport::OrderedOptions.new.merge(
12
+ presenter_name: presenter_name,
13
+ presents: presenter_name.singularize,
14
+ )
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,49 @@
1
+ module ActionPresenter
2
+ ActiveSupport.on_load(:action_view) do
3
+ ::ActionView::Base.class_eval do
4
+ # dynamic presenter initializer
5
+ def presenter(presenter_name, *params, &block)
6
+ instance_variable = "@#{presenter_name}_presenter"
7
+ presenter_instance = instance_variable_get(instance_variable)
8
+ # return presenter_instance if already initialized
9
+ return presenter_instance if presenter_instance
10
+ # initialize presenter instance
11
+ presenter_class_name = "#{presenter_name.camelize}Presenter"
12
+ presenter_class = ::ActionPresenter::Base::PRESENTER_CLASSES.find do |presenter_class|
13
+ presenter_class.name == presenter_class_name
14
+ end
15
+ raise ArgumentError, "#{presenter_class_name} is not defined" if !presenter_class
16
+ presenter = presenter_class.new.set(view: self)
17
+ instance_variable_set(instance_variable, presenter)
18
+ end
19
+
20
+ # controller presenter
21
+ def controller_presenter
22
+ return @controller_presenter if @controller_presenter
23
+ presenter_name = controller.presenter_options.presenter_name
24
+ @controller_presenter = presenter(presenter_name).tap do |new_presenter|
25
+ # attempt to auto set record
26
+ presents = new_presenter.presenter_options.presents
27
+ new_presenter.record ||= instance_variable_get("@#{new_presenter.presenter_options.presents}")
28
+ end
29
+ end
30
+
31
+ alias_method :cp, :controller_presenter
32
+
33
+ # local presenter
34
+ def local_presenter
35
+ @local_presenter || raise(ArgumentError, "local presenter [lp] must be provided")
36
+ end
37
+
38
+ def local_presenter=(new_local_presenter)
39
+ @local_presenter = new_local_presenter.tap do |new_presenter|
40
+ # attempt to auto set record
41
+ new_presenter.record ||= instance_variable_get("@#{new_presenter.presenter_options.presents}")
42
+ end
43
+ end
44
+
45
+ alias_method :lp, :local_presenter
46
+ alias_method :lp=, :local_presenter=
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,8 @@
1
+ class Hash
2
+ # dig value from nested hash using html name
3
+ def dig_html(name)
4
+ # convert "key1[key2][key3][]" => ["key1", "key2", "key3"]
5
+ parts = name.to_s.split(/\]\[|\[\]?|\]/)
6
+ parts.present? ? dig(*parts) : nil
7
+ end
8
+ end
@@ -0,0 +1,6 @@
1
+ class String
2
+ # convert "name1[name2]" to "name1_name2"
3
+ def slugify_html
4
+ scan(/[A-Za-z0-9]+/).join("_").underscore
5
+ end
6
+ end
@@ -0,0 +1,3 @@
1
+ module ActionPresenter
2
+ VERSION = "0.1.0"
3
+ end
metadata ADDED
@@ -0,0 +1,120 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: action_presenter-base
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Griffith Chaffee
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2018-03-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '5.1'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '5.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: actionview
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '5.1'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '5.1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.15'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.15'
55
+ - !ruby/object:Gem::Dependency
56
+ name: minitest
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '5.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '5.0'
69
+ description: Provides presenter logic to views.
70
+ email:
71
+ - griffithchaffee@gmail.com
72
+ executables: []
73
+ extensions: []
74
+ extra_rdoc_files: []
75
+ files:
76
+ - ".gitignore"
77
+ - ".travis.yml"
78
+ - CODE_OF_CONDUCT.md
79
+ - Gemfile
80
+ - LICENSE.txt
81
+ - README.md
82
+ - Rakefile
83
+ - action_presenter-base.gemspec
84
+ - bin/console
85
+ - bin/setup
86
+ - lib/action_presenter/base.rb
87
+ - lib/action_presenter/base/bootstrap.rb
88
+ - lib/action_presenter/base/form.rb
89
+ - lib/action_presenter/base/html.rb
90
+ - lib/action_presenter/railtie.rb
91
+ - lib/action_presenter/railtie/action_controller.rb
92
+ - lib/action_presenter/railtie/action_view.rb
93
+ - lib/action_presenter/ruby/hash.rb
94
+ - lib/action_presenter/ruby/string.rb
95
+ - lib/action_presenter/version.rb
96
+ homepage: https://github.com/griffithchaffee/action_presenter-base
97
+ licenses:
98
+ - MIT
99
+ metadata: {}
100
+ post_install_message:
101
+ rdoc_options: []
102
+ require_paths:
103
+ - lib
104
+ required_ruby_version: !ruby/object:Gem::Requirement
105
+ requirements:
106
+ - - ">="
107
+ - !ruby/object:Gem::Version
108
+ version: '0'
109
+ required_rubygems_version: !ruby/object:Gem::Requirement
110
+ requirements:
111
+ - - ">="
112
+ - !ruby/object:Gem::Version
113
+ version: '0'
114
+ requirements: []
115
+ rubyforge_project:
116
+ rubygems_version: 2.6.11
117
+ signing_key:
118
+ specification_version: 4
119
+ summary: Provides presenter logic to views.
120
+ test_files: []