lazy_value 0.0.1 → 0.0.3

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ef5939807537f53fd34ea59b921c2c35ad19b5cc0785ea85c5b02a83f16df684
4
- data.tar.gz: bf4cf993c42ae4b6a9201265ef0e20484e058bbc732ce2c3fa66d8218a89850a
3
+ metadata.gz: ff43403a1c22e54f42ccc10e23553ca1185da22aa520bd19239863da25be47fe
4
+ data.tar.gz: 38e5f11b43ff1b07d08df7f4e1530ce86f967d5ec51c6af7601414f0d3d41c25
5
5
  SHA512:
6
- metadata.gz: 53cc3085dc02b8b2369fefd8675fd9b581b0ee81ea7d0546f15280032bf5c651b7d16f872b21a62bb8d0afff7abb46929a2b0ca21063d1ccd285e7d97f9ce1bf
7
- data.tar.gz: e9c31654fa08c9049207e4c6948c6344fe74a1708dab053a5a6a9a7230586aac3a8858bce6193d732c774c3eb4276881b07daf26dace27aac5a453ebf14858bb
6
+ metadata.gz: 64c8b7a444814282cfaf80acb512405f2194b7f18dd388104e4ff3fcff601eb1dfd891d82d296571fd33b3121f8ab58f4322583bf741089f1d282747b2e5cb3a
7
+ data.tar.gz: 3d90984bba75aced80822d571450179b59580a4f3bf8764973a966de332a590062f0501a13a610d596e4e6b808d0b8dad838817d337f6750b85dfd9d74676f5d
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2023 Igor Kasyanchuk
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,129 @@
1
+ # Lazy Value
2
+
3
+ [![RailsJazz](https://github.com/igorkasyanchuk/rails_time_travel/blob/main/docs/my_other.svg?raw=true)](https://www.railsjazz.com)
4
+ [![Listed on OpenSource-Heroes.com](https://opensource-heroes.com/badge-v1.svg)](https://opensource-heroes.com/o/railsjazz)
5
+
6
+ ![RailsLiveReload](docs/lazy_value.gif)
7
+
8
+ Introducing a versatile value loader for your Ruby on Rails views, designed to optimize parallel loading of information on a page. This solution is perfect for scenarios where you need to display multiple stats, each taking 1-2 seconds to compute, thus causing a delay in page loading time.
9
+
10
+ Functioning similarly to lazy Turbo frames, this value loader has no reliance on Turbo and eliminates the need for creating new actions to load data. Make your page loading experience smoother and more efficient with this practical solution.
11
+
12
+ ## Main Benefits
13
+
14
+ 1. Just 1 line of code
15
+ 2. No reliance on JavaScript dependencies, such as Turbo
16
+ 3. Easy to implement with a "Plug & Play" approach
17
+ 4. Compatible with Turbo Frames
18
+
19
+ ## Essential Information & Constraints
20
+
21
+ 1. Currently compatible with ERB only
22
+ 2. Each lazy value should be atomic and not rely on any external value or variable initialized in the controller/view
23
+ 3. Limit usage to one lazy_value_tag per line
24
+ 4. Carefully follow the provided format when adding this block; refer to the README for guidance
25
+
26
+ ## Usage
27
+
28
+ It's strongly suggested to configure initializer (can be generated with `rails g lazy_value initializer`). You can put your credentials/secrets/env variable. It's needed to use the same encryption key between deploys or server instances.
29
+
30
+ ```ruby
31
+ LazyValue.setup do |config|
32
+ config.salt = ENV["LAZY_VALUE_SALT"].presence || SecureRandom.random_bytes(ActiveSupport::MessageEncryptor.key_len)
33
+ config.key = ENV["LAZY_VALUE_KEY"].presence || SecureRandom.hex(32)
34
+ end
35
+ ```
36
+
37
+ And now you can use `lazy_value_tag` helper in your views:
38
+
39
+ ```erb
40
+ <div class="column is-one-quarter">
41
+ <div class="box has-text-centered">
42
+ <h2 class="subtitle">Number 2</h2>
43
+ <%= lazy_value_tag do %>
44
+ <p class="title"><%= Project.pending.count %>%</p>
45
+ <% end %>
46
+ </div>
47
+ </div>
48
+ <div class="column is-one-quarter">
49
+ <div class="box has-text-centered">
50
+ <h2 class="subtitle">Number 3</h2>
51
+ <p class="title">
52
+ <%= lazy_value_tag { User.active.count } %>
53
+ </p>
54
+ </div>
55
+ </div>
56
+ ```
57
+
58
+ It also works with partials:
59
+
60
+ ```erb
61
+ <div class="box">
62
+ <%= lazy_value_tag do %>
63
+ <strong>Random 5 users</strong>
64
+ <%= render "/home/users", users: User.limit(5).order("random()") %>
65
+ <% end %>
66
+ </div>
67
+ ```
68
+
69
+ And even compatible with Turbo.
70
+
71
+ ```erb
72
+ <turbo-frame id="messages" target="_top">
73
+ This content is from lazy loaded turbo frame.
74
+
75
+ <%= lazy_value_tag do %>
76
+ <h3 class="title"><%= rand(1000) %></h3>
77
+ <% end %>
78
+
79
+ <%= lazy_value_tag do %>
80
+ <%= "I'm lazy loaded from the turbo frame" %>
81
+ <% end %>
82
+ </turbo-frame>
83
+ ```
84
+
85
+ ## Installation
86
+
87
+ Add this line to your application's Gemfile:
88
+
89
+ ```ruby
90
+ gem "lazy_value"
91
+ ```
92
+
93
+ And then execute:
94
+ ```bash
95
+ $ bundle
96
+ ```
97
+
98
+ And that is it. Start using it.
99
+
100
+ ## How it works
101
+
102
+ 1. We call `lazy_value_tag` in the view
103
+ 2. We save location from where it was called (with `caller_locations.first`), file + line number.
104
+ 3. We encrypt this info using `ActiveSupport::MessageEncryptor`, creating span with spinner, and JS snippet that will call `/lazy_value/show?payload=`
105
+ 4. In the controller we decrypt our data and reading ERB file and detecting our snippet
106
+ 5. Depending on the block syntax we evaluate ERB or Ruby.
107
+ 6. We return from the controller HTML that will replace snippen on the page.
108
+
109
+ ## Testing
110
+
111
+ `bin/rails test:system`.
112
+
113
+ ## TODO
114
+
115
+ - websockets options vs http
116
+ - pass variables
117
+ - change to modern JS?
118
+ - use POST? (if payload might be too big)
119
+
120
+ ## Contributing
121
+
122
+ You are welcome to contribute.
123
+
124
+ ## License
125
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
126
+
127
+
128
+ [<img src="https://github.com/igorkasyanchuk/rails_time_travel/blob/main/docs/more_gems.png?raw=true"
129
+ />](https://www.railsjazz.com/?utm_source=github&utm_medium=bottom&utm_campaign=rails_live_reload)
data/Rakefile ADDED
@@ -0,0 +1,7 @@
1
+ require "bundler/setup"
2
+
3
+ require "bundler/gem_tasks"
4
+
5
+ require_relative "test/dummy/config/application"
6
+
7
+ Rails.application.load_tasks
@@ -0,0 +1,39 @@
1
+ module LazyValue
2
+ class ApplicationController < ActionController::Base
3
+ REGEXP = /<%= lazy_value_tag(?:.*?)do %>(.*?)<% end %>|<%= lazy_value_tag { (.+?) } %>/m
4
+ ERROR_MESSAGE = "Incorrect usage. Try to use \"lazy_value_tag do ... end\" or \"lazy_value_tag { ... }\""
5
+
6
+ def show
7
+ matches = code.match(REGEXP)
8
+ if matches.present? && matches[1].present?
9
+ render plain: ActionController::Base.render(inline: matches[1])
10
+ elsif matches.present? && matches[2].present?
11
+ render plain: eval(matches[2])
12
+ else
13
+ render plain: ERROR_MESSAGE
14
+ end
15
+ end
16
+
17
+ private
18
+
19
+ def payload
20
+ Base64.urlsafe_decode64(params[:payload])
21
+ end
22
+
23
+ def code
24
+ data = JSON.parse(LazyValue.cryptography.decrypt_and_verify(payload))
25
+ # some security checks
26
+ raise "Incorrect file path" if data["path"] !~ /^#{Rails.root}/ || data["path"].include?("..")
27
+ # I want to return only first found lazy_value_tag snippet
28
+ snippet = File.read(data["path"]).lines[data["lineno"]-1..-1]
29
+ result = []
30
+ times = 0
31
+ snippet.map do |line|
32
+ times += 1 if line =~ /<%= lazy_value_tag/
33
+ break if times > 1
34
+ result << line
35
+ end
36
+ result.join
37
+ end
38
+ end
39
+ end
@@ -0,0 +1,59 @@
1
+ module LazyValue
2
+ module ApplicationHelper
3
+ SPINNER = <<~SVG
4
+ <svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><style>.spinner_OSmW{transform-origin:center;animation:spinner_T6mA .75s step-end infinite}@keyframes spinner_T6mA{8.3%{transform:rotate(30deg)}16.6%{transform:rotate(60deg)}25%{transform:rotate(90deg)}33.3%{transform:rotate(120deg)}41.6%{transform:rotate(150deg)}50%{transform:rotate(180deg)}58.3%{transform:rotate(210deg)}66.6%{transform:rotate(240deg)}75%{transform:rotate(270deg)}83.3%{transform:rotate(300deg)}91.6%{transform:rotate(330deg)}100%{transform:rotate(360deg)}}</style><g class="spinner_OSmW"><rect x="11" y="1" width="2" height="5" opacity=".14"/><rect x="11" y="1" width="2" height="5" transform="rotate(30 12 12)" opacity=".29"/><rect x="11" y="1" width="2" height="5" transform="rotate(60 12 12)" opacity=".43"/><rect x="11" y="1" width="2" height="5" transform="rotate(90 12 12)" opacity=".57"/><rect x="11" y="1" width="2" height="5" transform="rotate(120 12 12)" opacity=".71"/><rect x="11" y="1" width="2" height="5" transform="rotate(150 12 12)" opacity=".86"/><rect x="11" y="1" width="2" height="5" transform="rotate(180 12 12)"/></g></svg>
5
+ SVG
6
+
7
+ def lazy_value_tag(*args, &block)
8
+ element_id = "lazy_value_#{SecureRandom.hex(8)}"
9
+ kaller = caller_locations.first
10
+
11
+ options = {}
12
+ args.each { |e| options.merge!(e) if e.is_a?(Hash) }
13
+ options[:class] = [options[:class], "lazy-value-tag"].compact_blank.join(" ")
14
+ options[:id] = element_id
15
+
16
+ data = LazyValue.cryptography.encrypt_and_sign(
17
+ {
18
+ path: kaller.path,
19
+ lineno: kaller.lineno
20
+ }.to_json
21
+ )
22
+
23
+ content_tag(:span, raw(SPINNER), options) + raw(js_code(data, element_id))
24
+ end
25
+
26
+ private
27
+ def js_code(data, element_id)
28
+ <<~html
29
+ <script>
30
+ var remoteServerURL = "/lazy_value/show?payload=#{Base64.urlsafe_encode64(data)}"
31
+
32
+ function fetchRemoteContent#{element_id}() {
33
+ var xhr = new XMLHttpRequest();
34
+
35
+ xhr.onreadystatechange = function() {
36
+ if (xhr.readyState === XMLHttpRequest.DONE) {
37
+ if (xhr.status >= 200 && xhr.status < 400) {
38
+ var data = xhr.responseText; // Use JSON.parse(xhr.responseText) if the response is in JSON format
39
+ var contentContainer = document.getElementById('#{element_id}');
40
+ contentContainer.nextElementSibling.remove();
41
+ contentContainer.outerHTML = data;
42
+ //contentContainer.innerHTML = data;
43
+ } else {
44
+ console.error('Error fetching remote content:', xhr.status);
45
+ }
46
+ }
47
+ };
48
+
49
+ xhr.open('GET', remoteServerURL, true);
50
+ xhr.send();
51
+ }
52
+
53
+ fetchRemoteContent#{element_id}();
54
+ </script>
55
+ html
56
+ end
57
+
58
+ end
59
+ end
data/config/routes.rb ADDED
@@ -0,0 +1,7 @@
1
+ LazyValue::Engine.routes.draw do
2
+ get '/show' => 'application#show', as: :show
3
+ end
4
+
5
+ Rails.application.routes.draw do
6
+ mount_lazy_value_routes
7
+ end
@@ -0,0 +1,8 @@
1
+ Description:
2
+ Generate configuration file.
3
+
4
+ Example:
5
+ rails generate lazy_value initializer
6
+
7
+ This will create:
8
+ config/lazy_value.rb
@@ -0,0 +1,6 @@
1
+ class LazyValueGenerator < Rails::Generators::NamedBase
2
+ source_root File.expand_path('../templates', __FILE__)
3
+ def copy_initializer
4
+ template 'template.rb', 'config/initializers/lazy_value.rb'
5
+ end
6
+ end
@@ -0,0 +1,4 @@
1
+ LazyValue.setup do |config|
2
+ config.key = ENV["LAZY_VALUE_KEY"]
3
+ config.salt = ENV["LAZY_VALUE_SALT"]
4
+ end
@@ -0,0 +1,11 @@
1
+ module LazyValue
2
+ class Engine < ::Rails::Engine
3
+ isolate_namespace LazyValue
4
+
5
+ config.to_prepare do
6
+ ActiveSupport.on_load(:action_view) do
7
+ include LazyValue::ApplicationHelper
8
+ end
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,4 @@
1
+ module LazyValue
2
+ class Railtie < ::Rails::Railtie
3
+ end
4
+ end
@@ -0,0 +1,7 @@
1
+ module ActionDispatch::Routing
2
+ class Mapper
3
+ def mount_lazy_value_routes(options = {})
4
+ mount LazyValue::Engine => '/lazy_value', :as => options[:as] || 'lazy_value'
5
+ end
6
+ end
7
+ end
@@ -0,0 +1,3 @@
1
+ module LazyValue
2
+ VERSION = "0.0.3"
3
+ end
data/lib/lazy_value.rb ADDED
@@ -0,0 +1,30 @@
1
+ require "lazy_value/version"
2
+ require "lazy_value/routes"
3
+ require "lazy_value/engine"
4
+
5
+ module LazyValue
6
+ mattr_accessor :key
7
+ @@key = ENV["LAZY_VALUE_KEY"].presence || SecureRandom.hex(32)
8
+
9
+ mattr_accessor :salt
10
+ @@salt = ENV["LAZY_VALUE_SALT"].presence || SecureRandom.hex(8)
11
+
12
+ def self.setup
13
+ yield(self)
14
+ end
15
+
16
+ def self.cryptography
17
+ @cryptography ||= begin
18
+ ActiveSupport::MessageEncryptor.new(derived_key)
19
+ end
20
+ end
21
+
22
+ def self.derived_key
23
+ key_generator.generate_key(salt, 32)
24
+ end
25
+
26
+ def self.key_generator
27
+ ActiveSupport::KeyGenerator.new(key, iterations: 1000)
28
+ end
29
+
30
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :lazy_value do
3
+ # # Task goes here
4
+ # end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lazy_value
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1
4
+ version: 0.0.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Igor Kasyanchuk
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2023-04-16 00:00:00.000000000 Z
12
+ date: 2023-04-17 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: rails
@@ -130,7 +130,22 @@ email:
130
130
  executables: []
131
131
  extensions: []
132
132
  extra_rdoc_files: []
133
- files: []
133
+ files:
134
+ - MIT-LICENSE
135
+ - README.md
136
+ - Rakefile
137
+ - app/controllers/lazy_value/application_controller.rb
138
+ - app/helpers/lazy_value/application_helper.rb
139
+ - config/routes.rb
140
+ - lib/generators/lazy_value/USAGE
141
+ - lib/generators/lazy_value/lazy_value_generator.rb
142
+ - lib/generators/lazy_value/templates/template.rb
143
+ - lib/lazy_value.rb
144
+ - lib/lazy_value/engine.rb
145
+ - lib/lazy_value/railtie.rb
146
+ - lib/lazy_value/routes.rb
147
+ - lib/lazy_value/version.rb
148
+ - lib/tasks/lazy_value_tasks.rake
134
149
  homepage: https://github.com/railsjazz.com/lazy_value
135
150
  licenses:
136
151
  - MIT