compex 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: a05ce5e69574029faf2e79599fa9da036407cc795dbdbb0cdf1b61bee7207fa9
4
+ data.tar.gz: 2aafbe674927a37b3be6765eadb1728e034f0ccc5eb320c46c81cf67291d9e78
5
+ SHA512:
6
+ metadata.gz: c0b66d2086af516eff2747260fcde3d41442b9efac231b2f91d841f46e1022a1307ca0c3263a5eed4eba6ac94397cbaf73b404caeb346afd301ec2aa6d375321
7
+ data.tar.gz: ac8a634d182846d66e175a6fe99fced4ee9f9d0caf8500fe0ae0e6b077175690cff1cc5e6d9b97346d368b779db6a172176ad825ba0c7f7a98a7de051f4a898b
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,69 @@
1
+ plugins: rubocop-performance
2
+
3
+ AllCops:
4
+ TargetRubyVersion: 3.4
5
+ NewCops: enable
6
+ Exclude:
7
+ - vendor/**/*
8
+ SuggestExtensions: false
9
+
10
+ Style/StringLiterals:
11
+ EnforcedStyle: double_quotes
12
+
13
+ Style/StringLiteralsInInterpolation:
14
+ EnforcedStyle: double_quotes
15
+
16
+ Metrics/CyclomaticComplexity:
17
+ Enabled: false
18
+
19
+ Metrics/BlockLength:
20
+ Enabled: false
21
+
22
+ Metrics/PerceivedComplexity:
23
+ Enabled: false
24
+
25
+ Metrics/MethodLength:
26
+ Enabled: false
27
+
28
+ Metrics/AbcSize:
29
+ Enabled: false
30
+
31
+ Lint/MixedRegexpCaptureTypes:
32
+ Enabled: false
33
+
34
+ Layout/LineLength:
35
+ Enabled: false
36
+
37
+ Style/Documentation:
38
+ Enabled: false
39
+
40
+ Metrics/ModuleLength:
41
+ Enabled: false
42
+
43
+ Metrics/ClassLength:
44
+ Enabled: false
45
+
46
+ Layout/CaseIndentation:
47
+ EnforcedStyle: end
48
+
49
+ Layout/MultilineOperationIndentation:
50
+ EnforcedStyle: indented
51
+
52
+ Layout/SpaceAroundOperators:
53
+ EnforcedStyleForExponentOperator: space
54
+
55
+ Layout/EndAlignment:
56
+ EnforcedStyleAlignWith: start_of_line
57
+
58
+ Layout/FirstHashElementIndentation:
59
+ EnforcedStyle: consistent
60
+
61
+ Layout/FirstArrayElementIndentation:
62
+ EnforcedStyle: consistent
63
+
64
+ Layout/MultilineMethodCallIndentation:
65
+ EnforcedStyle: indented
66
+
67
+ Lint/UselessAssignment:
68
+ Exclude:
69
+ - spec/**/*
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, caste, color, religion, or sexual
10
+ identity and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the overall
26
+ community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or advances of
31
+ any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email address,
35
+ without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official email address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ [INSERT CONTACT METHOD].
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series of
86
+ actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or permanent
93
+ ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within the
113
+ community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
126
+ [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
data/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # CompEx
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ 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/CompEx`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ ```bash
14
+ bundle add UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
15
+ ```
16
+
17
+ If bundler is not being used to manage dependencies, install the gem by executing:
18
+
19
+ ```bash
20
+ gem install UPDATE_WITH_YOUR_GEM_NAME_IMMEDIATELY_AFTER_RELEASE_TO_RUBYGEMS_ORG
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, 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]/CompEx. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/CompEx/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the CompEx project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/CompEx/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
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
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CompEx
4
+ class AssetProvider
5
+ def self.provide(hashed)
6
+ return nil if !hashed.is_a?(String) || hashed.length < 2
7
+
8
+ case hashed[0]
9
+ when "j"
10
+ script = Cache.get_hashed_script(hashed[2...])
11
+ return nil unless script
12
+
13
+ script[1]
14
+ when "c"
15
+ style = Cache.get_hashed_style(hashed[2...])
16
+ return nil unless style
17
+
18
+ style[1]
19
+ end
20
+ end
21
+ end
22
+ end
data/lib/compex/bag.rb ADDED
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CompEx
4
+ class Bag
5
+ def initialize(parent, **args)
6
+ parent.defined_args.each do |arg|
7
+ next unless args.key? arg
8
+
9
+ define_singleton_method(arg) { args[arg] }
10
+ end
11
+ @_extra_css_hashes = []
12
+ @_extra_js_hashes = []
13
+ end
14
+
15
+ def extra_css_hashes = @_extra_css_hashes
16
+ def extra_js_hashes = @_extra_js_hashes
17
+
18
+ def render(klass, **args)
19
+ inst = klass.new(**args)
20
+ @_extra_css_hashes << inst.css_hash
21
+ @_extra_js_hashes << inst.js_hash
22
+ inst.render_html
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,219 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CompEx
4
+ class Base
5
+ class << self
6
+ def args(first, *rest)
7
+ [first, *rest].each { arg(it) }
8
+ self
9
+ end
10
+
11
+ def arg(first, *rest)
12
+ var_name = "@#{first}"
13
+ name = first
14
+ define_method(name) { instance_variable_get(var_name).to_s }
15
+ define_method("#{name}=") do |value|
16
+ instance_variable_set(var_name, UnsafeString.new(value))
17
+ end
18
+ @args ||= []
19
+ @args << name
20
+
21
+ return self if rest.empty?
22
+
23
+ warn "CompEx: #{self.name}: arg #{[first, *rest].join(", ")} should be args #{[first, *rest].join(", ")}"
24
+ rest.each { arg(it) }
25
+ self
26
+ end
27
+
28
+ def expose(first, *rest)
29
+ @exposed ||= []
30
+ @exposed << first
31
+ @exposed.append(*rest)
32
+ @exposed.uniq!
33
+ nil
34
+ end
35
+
36
+ def html(source)
37
+ @html = source
38
+ self
39
+ end
40
+
41
+ def style(source)
42
+ @style = source
43
+ self
44
+ end
45
+
46
+ def js(source)
47
+ @js = source
48
+ self
49
+ end
50
+
51
+ def raw_component_id
52
+ @raw_component_id ||= name || hash.to_s(36)
53
+ end
54
+
55
+ def component_id
56
+ @component_id ||= hash_string(raw_component_id)
57
+ end
58
+
59
+ def js_class_id
60
+ return @js_class_id if @js_class_id
61
+
62
+ class_id = name.split("::").map do |id|
63
+ next id unless id.start_with? "#"
64
+
65
+ hash_string(id)
66
+ end.join
67
+ @js_class_id ||= ["CompEx_", class_id, "_", component_id.upcase].join
68
+ end
69
+
70
+ def hash_string(str)
71
+ value = 2906
72
+ str.chars.map(&:ord).each do |v|
73
+ value = (value * 33) ^ v
74
+ end
75
+
76
+ (value & 0xFFFFFFFF).to_s(36)
77
+ end
78
+
79
+ def inherited(subclass)
80
+ super
81
+ CompEx::ComponentRegistry.register(subclass)
82
+ end
83
+
84
+ def stable_class_id(klass)
85
+ klass.name || Digest::SHA256.hexdigest(klass.inspect)
86
+ end
87
+
88
+ def defined_args
89
+ @args || []
90
+ end
91
+ end
92
+
93
+ using CompEx::StringRefinements
94
+
95
+ def html
96
+ @html ||= Cache.html(self.class) do
97
+ Template.parse(self.class.instance_variable_get(:@html) || find_template, self.class)
98
+ end
99
+ end
100
+
101
+ def style
102
+ self.class.instance_variable_get(:@style) || find_style
103
+ end
104
+
105
+ attr_reader :css, :css_hash, :js_hash, :js
106
+
107
+ def initialize(**args)
108
+ @bag = Bag.new(self, **args)
109
+ @extra_hashes = []
110
+
111
+ initialize_css
112
+ initialize_js
113
+ end
114
+
115
+ def exposed = self.class.instance_variable_get(:@exposed) || []
116
+
117
+ def initialize_css
118
+ css_id, css_source, css_hash = Cache.style(self.class) do
119
+ id, css = Style.compile(self, html.root_classes)
120
+ # Keeping define_css_prefix here, so we only define it once.
121
+ html.define_css_prefix(id)
122
+ css_hash = Digest::SHA1.hexdigest(css)
123
+ [id, css, "c_#{css_hash}"]
124
+ end
125
+ @css_id = css_id
126
+ @css = css_source
127
+ @css_hash = css_hash
128
+ end
129
+
130
+ def initialize_js
131
+ js = self.class.instance_variable_get(:@js) || find_js
132
+ return unless js
133
+
134
+ hash, src = Cache.script(self.class) do
135
+ js_hash = Digest::SHA1.hexdigest(js)
136
+ # Keeping define_js_module here, so we only define it once.
137
+ html.define_js_module(self.class.js_class_id)
138
+ ["j_#{js_hash}", JSRewriter.rewrite(self.class, js)]
139
+ end
140
+ @js = src
141
+ @js_hash = hash
142
+ end
143
+
144
+ def defined_args = self.class.defined_args
145
+
146
+ def render_html
147
+ html.render do |v|
148
+ case v
149
+ when Hash
150
+ inst = v[:component].new(**v[:args])
151
+ ret = inst.render_html do
152
+ v[:children]
153
+ end
154
+ @extra_hashes << inst.required_hashes
155
+ ret
156
+
157
+ when Proc
158
+ @bag.instance_exec(&v)
159
+ else
160
+ raise "Unexpected value of type #{v.class} provided by Renderer#render"
161
+ end
162
+ end
163
+ end
164
+
165
+ def required_hashes
166
+ [@css_hash, @js_hash, @bag.extra_css_hashes, @bag.extra_js_hashes, @extra_hashes]
167
+ .flatten
168
+ .compact
169
+ .uniq
170
+ end
171
+
172
+ def component_name
173
+ return nil if self.class.name.nil?
174
+
175
+ @component_name ||= self.class.name.split("::").map do |item|
176
+ next item if item[0] == "#"
177
+
178
+ item.underscore
179
+ end.join("/")
180
+ end
181
+
182
+ private
183
+
184
+ def find_template
185
+ path = CompEx.config.lookup_template(self, :html)
186
+ begin
187
+ File.read(path)
188
+ rescue Errno::ENOENT
189
+ raise "No template defined by #{self.class.name} (through ::html), nor could be found at #{path}"
190
+ end
191
+ end
192
+
193
+ def find_style
194
+ cname = component_name
195
+ return nil unless cname
196
+
197
+ path = CompEx.config.lookup_template(self, :style)
198
+ begin
199
+ style = File.read(path)
200
+ rescue Errno::ENOENT
201
+ return nil
202
+ end
203
+
204
+ Style.compile(style)
205
+ end
206
+
207
+ def find_js
208
+ cname = component_name
209
+ return nil unless cname
210
+
211
+ path = CompEx.config.lookup_template(self, :js)
212
+ begin
213
+ File.read(path)
214
+ rescue Errno::ENOENT
215
+ nil
216
+ end
217
+ end
218
+ end
219
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CompEx
4
+ class Cache
5
+ class Base
6
+ def prepare!(*, **) = nil
7
+ def prefix(key) = "#{CompEx.config.cache_prefix}#{key}"
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CompEx
4
+ class Cache
5
+ class MemcachedBackend
6
+ def prepare!(*, **)
7
+ begin
8
+ require "memcached"
9
+ rescue LoadError
10
+ raise "CompEx: Memcached cache mode requires the gem 'memcached' to be installed."
11
+ end
12
+ @instance = Memcached::Client.new(*, **)
13
+ end
14
+
15
+ def set(key, value) = @instance.set(prefix(key), value)
16
+ def get(key) = @instance.get(prefix(key))
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CompEx
4
+ class Cache
5
+ class MemoryBackend < Base
6
+ def prepare!(*, **)
7
+ @keys = {}
8
+ end
9
+
10
+ def set(key, value)
11
+ @keys[prefix(key)] = value
12
+ end
13
+
14
+ def get(key) = @keys[prefix(key)]
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CompEx
4
+ class Cache
5
+ class NoopBackend < Base
6
+ def get(*) = nil
7
+ def set(*) = nil
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CompEx
4
+ class Cache
5
+ class RedisBackend < Base
6
+ def prepare!(*, **)
7
+ begin
8
+ require "redis"
9
+ rescue LoadError
10
+ raise "CompEx: Redis cache mode requires the gem 'redis' to be installed."
11
+ end
12
+ @instance = Redis.new(*, **)
13
+ end
14
+
15
+ def set(key, value) = @instance.set(prefix(key), value)
16
+ def get(key) = @instance.get(prefix(key))
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "cache/base"
4
+ require_relative "cache/memcached_backend"
5
+ require_relative "cache/memory_backend"
6
+ require_relative "cache/noop_backend"
7
+ require_relative "cache/redis_backend"
8
+
9
+ module CompEx
10
+ class Cache
11
+ class << self
12
+ def backend = CompEx.config.cache_backend
13
+ def stable_class_id(comp) = CompEx::Base.stable_class_id(comp)
14
+
15
+ def style(component_class)
16
+ stable_id = stable_class_id(component_class)
17
+ stable_key = "style:#{stable_id}"
18
+ v = backend.get(stable_key)
19
+ return JSON.parse(v, symbolize_names: true) if v
20
+
21
+ r = yield
22
+ backend.set("style:#{r.last[2...]}", stable_id)
23
+ backend.set(stable_key, r.to_json)
24
+
25
+ r
26
+ end
27
+
28
+ def get_hashed_style(hashed)
29
+ ptr = backend.get("style:#{hashed}")
30
+ return nil unless ptr
31
+
32
+ v = backend.get("style:#{ptr}")
33
+ return nil unless v
34
+
35
+ JSON.parse(v, symbolize_names: true)
36
+ end
37
+
38
+ def html(component_class)
39
+ stable_id = stable_class_id(component_class)
40
+ stable_key = "html:#{stable_id}"
41
+ v = backend.get(stable_key)
42
+ return v if v
43
+
44
+ html = yield
45
+ backend.set(stable_key, html)
46
+
47
+ html
48
+ end
49
+
50
+ def script(component_class)
51
+ stable_id = stable_class_id(component_class)
52
+ stable_key = "script:#{stable_id}"
53
+ v = backend.get(stable_key)
54
+ return JSON.parse(v, symbolize_names: true) if v
55
+
56
+ r = yield
57
+ backend.set(stable_key, r.to_json)
58
+ backend.set("script:#{r.first[2...]}", stable_id)
59
+
60
+ r
61
+ end
62
+
63
+ def get_hashed_script(hashed)
64
+ ptr = backend.get("script:#{hashed}")
65
+ return nil unless ptr
66
+
67
+ v = backend.get("script:#{ptr}")
68
+ return nil unless v
69
+
70
+ JSON.parse(v, symbolize_names: true)
71
+ end
72
+ end
73
+ end
74
+ end