├── .gitignore
├── lib
├── render_react
│ ├── version.rb
│ └── context.rb
└── render_react.rb
├── Gemfile
├── CHANGELOG.md
├── spec
├── fixtures
│ └── example_component.js
└── render_react_spec.rb
├── .github
└── workflows
│ └── test.yml
├── render_react.gemspec
├── MIT-LICENSE.txt
├── Rakefile
├── CODE_OF_CONDUCT.md
└── README.md
/.gitignore:
--------------------------------------------------------------------------------
1 | Gemfile.lock
2 | /pkg
3 |
--------------------------------------------------------------------------------
/lib/render_react/version.rb:
--------------------------------------------------------------------------------
1 | # frozen_string_literal: true
2 |
3 | module RenderReact
4 | VERSION = "1.0.2"
5 | end
6 |
--------------------------------------------------------------------------------
/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | gemspec
4 |
5 | gem 'minitest'
6 | gem 'minitest-reporters'
7 | gem 'rake'
8 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | ## CHANGELOG
2 |
3 | ### 1.0.2
4 |
5 | * Relax Ruby version requirement to allow Ruby 3.0
6 |
7 | ### 1.0.1
8 |
9 | * Allow client-only mode by not passing any server-side context
10 |
11 | ### 1.0.0
12 |
13 | * Initial release
14 |
15 |
--------------------------------------------------------------------------------
/spec/fixtures/example_component.js:
--------------------------------------------------------------------------------
1 | import React from 'react'
2 | import ReactDOM from 'react-dom'
3 | import ReactDOMServer from 'react-dom/server'
4 |
5 | class ExampleComponent extends React.Component {
6 | render() {
7 | return
8 | }
9 | }
10 |
11 | export default {
12 | React: React,
13 | ReactDOM: ReactDOM,
14 | ReactDOMServer: ReactDOMServer,
15 | components: {
16 | ExampleComponent: ExampleComponent,
17 | }
18 | }
19 |
20 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: Test
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | test:
7 | name: Ruby ${{ matrix.ruby }} (${{ matrix.os }})
8 | if: "!contains(github.event.head_commit.message, '[skip ci]')"
9 | strategy:
10 | matrix:
11 | ruby:
12 | - 3.0
13 | - 2.7
14 | - 2.6
15 | - 2.5
16 | - jruby-9.2.13.0
17 | - truffleruby-20.3.0
18 | os:
19 | - ubuntu-latest
20 | runs-on: ${{matrix.os}}
21 | steps:
22 | - uses: actions/checkout@v2
23 | - name: Set up Ruby
24 | uses: ruby/setup-ruby@v1
25 | with:
26 | ruby-version: ${{matrix.ruby}}
27 | bundler-cache: true
28 | - name: Run tests
29 | run: bundle exec rake
30 |
--------------------------------------------------------------------------------
/lib/render_react.rb:
--------------------------------------------------------------------------------
1 | require_relative "render_react/version"
2 | require_relative "render_react/context"
3 |
4 | module RenderReact
5 | class << self
6 | def context
7 | @context or raise ArgumentError, "Create a RenderReact::Context via RenderReact.create_context! first!"
8 | end
9 |
10 | def create_context!(*args)
11 | @context = Context.new(*args)
12 | end
13 |
14 | def render_react(*args)
15 | context.render_react(*args)
16 | end
17 | alias call render_react
18 |
19 | def on_server(*args)
20 | context.on_server(*args)
21 | end
22 |
23 | def on_client(*args)
24 | context.on_client(*args)
25 | end
26 |
27 | def on_client_and_server(*args)
28 | context.on_client_and_server(*args)
29 | end
30 |
31 | def on_server_and_client(*args)
32 | context.on_server_and_client(*args)
33 | end
34 | end
35 | end
--------------------------------------------------------------------------------
/render_react.gemspec:
--------------------------------------------------------------------------------
1 | # -*- encoding: utf-8 -*-
2 |
3 | require File.dirname(__FILE__) + "/lib/render_react/version"
4 |
5 | Gem::Specification.new do |gem|
6 | gem.name = "render_react"
7 | gem.version = RenderReact::VERSION
8 | gem.summary = "Lo-fi way of rendering React components"
9 | gem.description = "Lo-fi way of rendering React components."
10 | gem.authors = ["Jan Lelis"]
11 | gem.email = ["hi@ruby.consulting"]
12 | gem.homepage = "https://github.com/janlelis/render_react"
13 | gem.license = "MIT"
14 |
15 | gem.files = Dir["{**/}{.*,*}"].select{ |path| File.file?(path) && path !~ /^(pkg|spec)/ }
16 | gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
17 | gem.test_files = gem.files.grep(%r{^(test|spec|features)/})
18 | gem.require_paths = ["lib"]
19 |
20 | gem.required_ruby_version = ">= 2.0"
21 | gem.add_dependency "execjs", "~> 2.7"
22 | end
23 |
--------------------------------------------------------------------------------
/MIT-LICENSE.txt:
--------------------------------------------------------------------------------
1 | Copyright (c) 2017 Jan Lelis, https://janlelis.com
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.
21 |
--------------------------------------------------------------------------------
/Rakefile:
--------------------------------------------------------------------------------
1 | # # #
2 | # Get gemspec info
3 |
4 | gemspec_file = Dir['*.gemspec'].first
5 | gemspec = eval File.read(gemspec_file), binding, gemspec_file
6 | info = "#{gemspec.name} | #{gemspec.version} | " \
7 | "#{gemspec.runtime_dependencies.size} dependencies | " \
8 | "#{gemspec.files.size} files"
9 |
10 | # # #
11 | # Gem build and install task
12 |
13 | desc info
14 | task :gem do
15 | puts info + "\n\n"
16 | print " "; sh "gem build #{gemspec_file}"
17 | FileUtils.mkdir_p 'pkg'
18 | FileUtils.mv "#{gemspec.name}-#{gemspec.version}.gem", 'pkg'
19 | puts; sh %{gem install --no-document pkg/#{gemspec.name}-#{gemspec.version}.gem}
20 | end
21 |
22 | # # #
23 | # Start an IRB session with the gem loaded
24 |
25 | desc "#{gemspec.name} | IRB"
26 | task :irb do
27 | sh "irb -I ./lib -r #{gemspec.name.gsub '-','/'}"
28 | end
29 |
30 | # # #
31 | # Run Specs
32 |
33 | desc "#{gemspec.name} | Spec"
34 | task :spec do
35 | if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
36 | sh "for %f in (spec/\*.rb) do ruby spec/%f"
37 | else
38 | sh "for file in spec/*.rb; do ruby $file; done"
39 | end
40 | end
41 | task default: :spec
42 |
43 |
--------------------------------------------------------------------------------
/lib/render_react/context.rb:
--------------------------------------------------------------------------------
1 | require "execjs"
2 | require "securerandom"
3 | require "json"
4 |
5 | module RenderReact
6 | class Context
7 | attr_reader :app, :mode
8 |
9 | def initialize(javascript_source = nil, mode: :client_and_server)
10 | if javascript_source == nil
11 | @app = nil
12 | @mode = :client_only
13 | else
14 | @app = ExecJS.compile(javascript_source)
15 | @mode = mode
16 | end
17 | end
18 |
19 | def render_react(*args)
20 | case mode
21 | when :client, :client_only
22 | on_client(*args)
23 | when :server
24 | on_server(*args)
25 | when :client_and_server, :server_and_client
26 | on_client_and_server(*args)
27 | else
28 | raise ArgumentError, "unknown render mode"
29 | end
30 | end
31 | alias call render_react
32 |
33 | def on_client(component_name, props_hash = {})
34 | component_uuid = SecureRandom.uuid
35 | props_json = JSON.dump(props_hash)
36 | "
"
37 | end
38 |
39 | def on_server(component_name, props_hash = {})
40 | if mode == :client_only
41 | raise ArgumentError, "Context mode is :client_only, create a server context to be able to use server-side rendering"
42 | end
43 |
44 | props_json = JSON.dump(props_hash)
45 | app.eval(server_script(component_name, props_json, true))
46 | end
47 |
48 | def on_client_and_server(component_name, props_hash = {})
49 | if mode == :client_only
50 | raise ArgumentError, "Context mode is :client_only, create a server context to be able to use server-side rendering"
51 | end
52 |
53 | component_uuid = SecureRandom.uuid
54 | props_json = JSON.dump(props_hash)
55 | server_rendered = app.eval(server_script(component_name, props_json))
56 | "#{server_rendered}
"
57 | end
58 | alias on_server_and_client on_client_and_server
59 |
60 | private
61 |
62 | def client_script(component_name, props_json, uuid)
63 | "RenderReact.ReactDOM.render(RenderReact.React.createElement(RenderReact.components.#{component_name}, #{props_json}), document.getElementById('RenderReact-#{uuid}'))"
64 | end
65 |
66 | def server_script(component_name, props_json, static = false)
67 | render_method = static ? 'renderToStaticMarkup' : 'renderToString'
68 | "RenderReact.ReactDOMServer.#{render_method}(RenderReact.React.createElement(RenderReact.components.#{component_name}, #{props_json}))"
69 | end
70 | end
71 | end
72 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
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 opensource@janlelis.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/
75 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # RenderReact [![[version]](https://badge.fury.io/rb/render_react.svg)](https://badge.fury.io/rb/render_react) [![[ci]](https://github.com/janlelis/render_react/workflows/Test/badge.svg)](https://github.com/janlelis/render_react/actions?query=workflow%3ATest)
2 |
3 | A lo-fi way to render client- and server-side React components from Ruby:
4 |
5 | ```js
6 | class ExampleComponent extends React.Component {
7 | render() {
8 | return
9 | }
10 | }
11 | ```
12 |
13 | ```html
14 | RenderReact.on_client_and_server("ExampleComponent", { example: "!" })
15 | # =>
16 |
17 |
20 |
21 |
29 | ```
30 |
31 | It is *bring your own tooling*: React is not included, nor any ES6 transpilers or module bundlers. It expects you to prepare the JavaScript bundle file in a specific format, which must contain React and all of your components.
32 |
33 | If you are looking for higher-level alternatives, checkout [react_on_rails](https://github.com/shakacode/react_on_rails) or [react-rails](https://github.com/reactjs/react-rails).
34 |
35 | ## Setup
36 |
37 | Add to your `Gemfile`:
38 |
39 | ```ruby
40 | gem 'render_react'
41 | ```
42 |
43 | ### JavaScript Source Preparation
44 |
45 | **RenderReact** expects the JavaScript bundle to include a global variable called `RenderReact` with the following contents:
46 |
47 | ```javascript
48 | {
49 | React: [variable which contains React],
50 | ReactDOM: [variable which contains ReactDOM],
51 | ReactDOMServer: [variable which contains ReactDOMServer],
52 | components: {
53 | ComponentIdentifier1: [variable which contains the component 1],
54 | ComponentIdentifier2: [variable which contains the component 2],
55 | ...
56 | }
57 | }
58 | ```
59 |
60 | - Where is **React**? See first paragraph of https://facebook.github.io/react/docs/react-api.html
61 | - Where is **ReactDOM**? See first paragraph of https://facebook.github.io/react/docs/react-dom.html
62 | - Where is **ReactDOMServer**? See first paragraph of https://facebook.github.io/react/docs/react-dom-server.html
63 |
64 | You can have two different javascript bundle files - one for server rendering, and one for client-rendering.
65 |
66 | - The client bundle has to be included into your application by a method of your choice. You may skip passing in `ReactDOMServer` for the client bundle
67 | - The server bundle has to be passed to `RenderReact` (see Usage section). You may skip passing in `ReactDOM` for the server bundle
68 |
69 | #### Example (With ES6 Modules)
70 |
71 | ```javascript
72 | import React from 'react'
73 | import ReactDOM from 'react-dom'
74 | import ReactDOMServer from 'react-dom/server'
75 |
76 | import ExampleComponent from './components/example_component'
77 |
78 | export default {
79 | React: React,
80 | ReactDOM: ReactDOM,
81 | ReactDOMServer: ReactDOMServer,
82 | components: {
83 | ExampleComponent: ExampleComponent
84 | }
85 | }
86 | ```
87 |
88 | Gets imported as `RenderReact`
89 |
90 | #### Example (With Browser Globals)
91 |
92 | ```javascript
93 | window.RenderReact = {
94 | React: React,
95 | ReactDOM: ReactDOM,
96 | ReactDOMServer: ReactDOMServer,
97 | components: {
98 | ExampleComponent: ExampleComponent
99 | }
100 | }
101 | ```
102 |
103 | ## Usage
104 |
105 | Create a **RenderReact** context by passing your server-side JavaScript bundle:
106 |
107 | ```ruby
108 | RenderReact.create_context! File.read('path/to/your/server-bundle.js'), mode: :client_and_server
109 | ```
110 |
111 | You can use it without a server-side bundle by not passing any file source.
112 |
113 | The optional `mode:` keyword argument can have one of the following values
114 |
115 | - `:client_and_server` (default) - component will be rendered server-side and mounted in the client
116 | - `:client` - component will be mounted in the client
117 | - `:server` - component will be render statically
118 |
119 | You can then render a component with
120 |
121 | ```ruby
122 | RenderReact.("ExampleComponent", { example: "prop" })
123 | ```
124 |
125 | It is possible to overwrite the context-rendering-mode by using specfic render methods:
126 |
127 | ```ruby
128 | RenderReact.on_client_and_server("ExampleComponent") # server- and client-side
129 | RenderReact.on_client("ExampleComponent") # only client-side
130 | RenderReact.on_server("ExampleComponent") # only static
131 | ```
132 |
133 | ## MIT License
134 |
135 | Copyright (C) 2017 Jan Lelis . Released under the MIT license.
136 |
137 | React is BSD licensed.
138 |
--------------------------------------------------------------------------------
/spec/render_react_spec.rb:
--------------------------------------------------------------------------------
1 | require_relative "../lib/render_react"
2 | require "minitest/reporters"
3 | require "minitest/autorun"
4 |
5 | Minitest::Reporters.use! \
6 | Minitest::Reporters::SpecReporter.new
7 |
8 | describe "RenderReact" do
9 | EXAMPLE_JAVASCRIPT_APP_PATH = File.dirname(__FILE__) + "/fixtures/react_and_example_component.js"
10 |
11 | before do
12 | RenderReact.instance_variable_set(:@context, nil)
13 | end
14 |
15 | it "needs a context before it works" do
16 | assert_raises(ArgumentError){
17 | RenderReact.("ExampleComponent", example: "prop")
18 | }
19 | end
20 |
21 | it "create a new context with .create_context!" do
22 | res = RenderReact.create_context!("// some javascript which sets up the RenderReact variable")
23 | assert_instance_of RenderReact::Context, res
24 | end
25 |
26 | describe "[has JS source as context]" do
27 | before do
28 | source = File.read(EXAMPLE_JAVASCRIPT_APP_PATH)
29 | RenderReact.create_context!(source)
30 | end
31 |
32 | it "'s current context in avaible as .context" do
33 | assert_instance_of RenderReact::Context, RenderReact.context
34 | end
35 |
36 | it "delegates .render_react (aliased as .call) method to context" do
37 | fake_context = RenderReact.instance_variable_set(:@context, Minitest::Mock.new)
38 | fake_context.expect(:render_react, true, ["ExampleComponent"])
39 |
40 | RenderReact.("ExampleComponent")
41 | fake_context.verify
42 | end
43 |
44 | it "delegates .on_* methods to context" do
45 | fake_context = RenderReact.instance_variable_set(:@context, Minitest::Mock.new)
46 |
47 | fake_context.expect(:on_client, true, ["ExampleComponent"])
48 | fake_context.expect(:on_server, true, ["ExampleComponent"])
49 | fake_context.expect(:on_client_and_server, true, ["ExampleComponent"])
50 | fake_context.expect(:on_server_and_client, true, ["ExampleComponent"])
51 |
52 | RenderReact.on_server("ExampleComponent")
53 | RenderReact.on_client("ExampleComponent")
54 | RenderReact.on_client_and_server("ExampleComponent")
55 | RenderReact.on_server_and_client("ExampleComponent")
56 |
57 | fake_context.verify
58 | end
59 | end
60 |
61 | describe "Context" do
62 | describe "#render_react / #call" do
63 | it "delegates to render_client_and_server if mode is :client_and_server" do
64 | context = RenderReact::Context.new(File.read(EXAMPLE_JAVASCRIPT_APP_PATH), mode: :client_and_server)
65 | called = false
66 | context.define_singleton_method :on_client_and_server do |*|
67 | called = true
68 | end
69 | context.render_react("ExampleComponent")
70 |
71 | assert called
72 | end
73 |
74 | it "delegates to render_client if mode is :client" do
75 | context = RenderReact::Context.new(File.read(EXAMPLE_JAVASCRIPT_APP_PATH), mode: :client)
76 | called = false
77 | context.define_singleton_method :on_client do |*|
78 | called = true
79 | end
80 | context.render_react("ExampleComponent")
81 |
82 | assert called
83 | end
84 |
85 | it "delegates to render_server if mode is :server" do
86 | context = RenderReact::Context.new(File.read(EXAMPLE_JAVASCRIPT_APP_PATH), mode: :server)
87 | called = false
88 | context.define_singleton_method :on_server do |*|
89 | called = true
90 | end
91 | context.render_react("ExampleComponent")
92 |
93 | assert called
94 | end
95 | end
96 |
97 | describe "#render_client_and_server" do
98 | it "renders HTML code for mounting the React component in the client and also renders it to HTML via ReactDOMServer.renderToString" do
99 | context = RenderReact::Context.new(File.read(EXAMPLE_JAVASCRIPT_APP_PATH))
100 | res = context.on_client_and_server("ExampleComponent", example: "!")
101 | assert_match /.*Hello Ruby.*!.*<\/marquee>/, res
102 | assert_match /RenderReact.ReactDOM.render\(RenderReact.React.createElement\(RenderReact.components.ExampleComponent, {\"example\":\"!\"}\), document.getElementById\('RenderReact-.*/, res
103 | end
104 | end
105 |
106 | describe "#render_client" do
107 | it "renders HTML code for mounting the React component in the client" do
108 | context = RenderReact::Context.new(File.read(EXAMPLE_JAVASCRIPT_APP_PATH))
109 | res = context.on_client("ExampleComponent", example: "!")
110 | assert_match /
RenderReact.ReactDOM.render\(RenderReact.React.createElement\(RenderReact.components.ExampleComponent, {\"example\":\"!\"}\), document.getElementById\('RenderReact-.*/, res
111 | end
112 | end
113 |
114 | describe "#render_server" do
115 | it "renders a React component to static HTML via ReactDOMServer.renderToStaticMarkup" do
116 | context = RenderReact::Context.new(File.read(EXAMPLE_JAVASCRIPT_APP_PATH))
117 | res = context.on_server("ExampleComponent", example: "!")
118 | assert_match /