Nat  Grady

Nat Grady

1660708935

Usethis: Set Up Commonly Used Components

usethis

usethis is a workflow package: it automates repetitive tasks that arise during project setup and development, both for R packages and non-package projects.

Installation

Install the released version of usethis from CRAN:

install.packages("usethis")

Or install the development version from GitHub with:

# install.packages("devtools")
devtools::install_github("r-lib/usethis")

Usage

Most use_*() functions operate on the active project: literally, a directory on your computer. If you’ve just used usethis to create a new package or project, that will be the active project. Otherwise, usethis verifies that current working directory is or is below a valid project directory and that becomes the active project. Use proj_get() or proj_sitrep() to manually query the project and read more in the docs.

A few usethis functions have no strong connections to projects and will expect you to provide a path.

usethis is quite chatty, explaining what it’s doing and assigning you tasks. indicates something usethis has done for you. indicates that you’ll need to do some work yourself.

Below is a quick look at how usethis can help to set up a package. But remember, many usethis functions are also applicable to analytical projects that are not packages.

library(usethis)

# Create a new package -------------------------------------------------
path <- file.path(tempdir(), "mypkg")
create_package(path)
#> ✔ Creating '/tmp/Rtmp4VMzwK/mypkg/'
#> ✔ Setting active project to '/private/tmp/Rtmp4VMzwK/mypkg'
#> ✔ Creating 'R/'
#> ✔ Writing 'DESCRIPTION'
#> Package: mypkg
#> Title: What the Package Does (One Line, Title Case)
#> Version: 0.0.0.9000
#> Authors@R (parsed):
#>     * First Last <first.last@example.com> [aut, cre] (YOUR-ORCID-ID)
#> Description: What the package does (one paragraph).
#> License: `use_mit_license()`, `use_gpl3_license()` or friends to pick a
#>     license
#> Encoding: UTF-8
#> Roxygen: list(markdown = TRUE)
#> RoxygenNote: 7.2.0
#> ✔ Writing 'NAMESPACE'
#> ✔ Setting active project to '<no active project>'
# only needed since this session isn't interactive
proj_activate(path)
#> ✔ Setting active project to '/private/tmp/Rtmp4VMzwK/mypkg'
#> ✔ Changing working directory to '/tmp/Rtmp4VMzwK/mypkg/'

# Modify the description ----------------------------------------------
use_mit_license("My Name")
#> ✔ Setting License field in DESCRIPTION to 'MIT + file LICENSE'
#> ✔ Writing 'LICENSE'
#> ✔ Writing 'LICENSE.md'
#> ✔ Adding '^LICENSE\\.md$' to '.Rbuildignore'

use_package("ggplot2", "Suggests")
#> ✔ Adding 'ggplot2' to Suggests field in DESCRIPTION
#> • Use `requireNamespace("ggplot2", quietly = TRUE)` to test if package is installed
#> • Then directly refer to functions with `ggplot2::fun()`

# Set up other files -------------------------------------------------
use_readme_md()
#> ✔ Writing 'README.md'
#> • Update 'README.md' to include installation instructions.

use_news_md()
#> ✔ Writing 'NEWS.md'

use_test("my-test")
#> ✔ Adding 'testthat' to Suggests field in DESCRIPTION
#> ✔ Setting Config/testthat/edition field in DESCRIPTION to '3'
#> ✔ Creating 'tests/testthat/'
#> ✔ Writing 'tests/testthat.R'
#> ✔ Writing 'tests/testthat/test-my-test.R'
#> • Edit 'tests/testthat/test-my-test.R'

x <- 1
y <- 2
use_data(x, y)
#> ✔ Adding 'R' to Depends field in DESCRIPTION
#> ✔ Creating 'data/'
#> ✔ Setting LazyData to 'true' in 'DESCRIPTION'
#> ✔ Saving 'x', 'y' to 'data/x.rda', 'data/y.rda'
#> • Document your data (see 'https://r-pkgs.org/data.html')

# Use git ------------------------------------------------------------
use_git()
#> ✔ Initialising Git repo
#> ✔ Adding '.Rproj.user', '.Rhistory', '.Rdata', '.httr-oauth', '.DS_Store' to '.gitignore'

Code of Conduct

Please note that the usethis project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

Download Details:

Author: r-lib
Source Code: https://github.com/r-lib/usethis 
License: Unknown, MIT licenses found

#r #github #setup 

Usethis: Set Up Commonly Used Components
Reid  Rohan

Reid Rohan

1660101000

Setup GitHub Actions Workflow with A Specific Version Of Bun

action-setup-bun

Setup GitHub Actions workflow with a specific version of Bun and add $BUN_INSTALL/bin to the $PATH.

Requirements

  • macOS x64 & Silicon, Linux x64, Windows Subsystem for Linux

Usage

- name: Setup Bun Runtime
  uses: antongolub/action-setup-bun@v1 # or @v1.x.x
  with:
    # Optional, if empty the latest bun version will be used
    # Examples: 0.0.77, 0.1.2, >=0.1, *
    bun-version: 0.1.2

    # Optional, default is 'Jarred-Sumner/bun-releases-for-updater'
    # Example: oven-sh/misc-test-builds
    bun-repo: 'Jarred-Sumner/bun-releases-for-updater'

    # Override bunfig.toml inners
    # Optional. JSON-formatted string as input
    # See: https://github.com/oven-sh/bun#bunfigtoml
    bun-config: '{"install: {"production": false}}'
    
    # Attach $BUN_INSTALL/install/cache to action/cache
    # Optional, defaults to false
    cache: true

    # actions/tool-cache provides a cache for the current job only
    # Use actions/cache to store the bun binary for the whole workflow
    # Optional, defaults to false
    cache-bin: true

    # Optional, default is process.platform
    # Examples: darwin, linux
    platform: 'linux'

    # Optional, default is process.arch
    # Examples: x64, arm64
    arch: 'x64'
    
    # Authenticated requests get a higher rate limit
    # Optional. Defaults to ${{ github.token }}
    token: 'gh-token'

- name: Run script
  run: bun index.js

bun-repo

There are at least 3 known places to fetch bun distributions:

$HOME

The env.HOME is used to store the bun binary (${HOME}/.bun/bin). If you want to assign another directory, you can override this env option.

env:
  HOME: '/custom/path'

Outputs

NameDescription
bun-versionThe version of Bun that was installed
cache-hitif the bun cache was hit: true / false
errorif an error occurred, the error message

Debug

This flag can be enabled by setting the secret ACTIONS_STEP_DEBUG to true.

Download Details:

Author: Antongolub
Source Code: https://github.com/antongolub/action-setup-bun 
License: MIT license

#typescript #setup #action #github 

Setup GitHub Actions Workflow with A Specific Version Of Bun
Reid  Rohan

Reid Rohan

1660086120

Set Up Your GitHub Actions Workflow with A Specific Version Of Bun

setup-bun

Huge inspiration setup-deno

Set up your GitHub Actions workflow with a specific version of Bun.

Usage

Latest stable

- uses: xhyrom/setup-bun@v0.1.7
  with:
    bun-version: latest
    github-token: ${{ secrets.GITHUB_TOKEN }}

Specific version

- uses: xhyrom/setup-bun@v0.1.7
  with:
    bun-version: "0.1.5"
    github-token: ${{ secrets.GITHUB_TOKEN }}

Canary builds

- uses: xhyrom/setup-bun@v0.1.7
  with:
    bun-version: canary
    github-token: ${{ secrets.GITHUB_TOKEN }}

Custom repository

- uses: xhyrom/setup-bun@v0.1.7
  with:
    repository: https://github.com/oven-sh/misc-test-builds
    github-token: ${{ secrets.GITHUB_TOKEN }}

Custom download url

- uses: xhyrom/setup-bun@v0.1.7
  with:
    custom-download-url: https://api.github.com/repos/oven-sh/bun/actions/artifacts/311939881/zip # must be github api
    github-token: ${{ secrets.GITHUB_TOKEN }}

Download Details:

Author: xHyroM
Source Code: https://github.com/xHyroM/setup-bun 
License: MIT license

#typescript #setup #github 

Set Up Your GitHub Actions Workflow with A Specific Version Of Bun

Cakephp-vagrant-setup: CakePHP 3 Vagrant Setup Made Simple

Vagrant Setup for CakePHP 3.x

This will generate the config files needed to get your vagrant environment setup for cakePHP running on Ubuntu 20.04 with PHP 7.4 on nginx.

Prerequisites

  • Virtualbox >= 6.1
  • Vagrant >= 2.2.10
  • Git
  • Root access to your local machine

Running the generator

To run the generator use the following command:

curl -sS https://raw.githubusercontent.com/cpierce/cakephp-vagrant-setup/master/scripts/vagrant_setup.php | php -- --ip 192.168.33.77 --hostname dev.cpierce.org

After the Vagrant file is created you can simply use the vagrant up command to start provisioning your local environment!

This will install the Vagrantfile you'll need. All available options are listed in the table below.

OptionDescriptionExample
ipIP Address for your virtual machine to use.--ip 192.168.33.77
hostnameHostname to use for virtual environment.--hostname dev.cpierce.org
memory-limitAmount of memory in MB virtual environment should consume when running.--memory-limit 1024
cpu-limitNumber of virtual CPUs to give virtual environment.--cpu-limit 1
skip-hostSkip the echo of the hostfile information if you don't want to do the sudo tee -a /etc/hosts part or do the host setup manually.--skip-host

Note: While you can have multiple hosts with the same IP Address, you cannot run them at the same time so it is always recommended to change the host IP Address for each configuration you setup. Note: Also thanks to Google making .dev (TLD) a require https on the HSTS you'll now have to either use another tld that isn't real or just do what I've been doing and update the dns for your domain such as dev.cpierce.org. One benefit of this is that you don't have to make changes to your host file and multiple people can use the same dev hostname. If you don't know how to do this you are welcome to use the default http://dev.cpierce.org/ to develop with.

Author: cpierce
Source Code: https://github.com/cpierce/cakephp-vagrant-setup 
License: MIT license

#php #cakephp #setup 

Cakephp-vagrant-setup: CakePHP 3 Vagrant Setup Made Simple

React-rails: integrate React.js with Rails Views and Controllers

React-Rails  

React-Rails is a flexible tool to use React with Rails. The benefits:

  • Automatically renders React server-side and client-side
  • Supports Webpacker 4.x, 3.x, 2.x, 1.1+
  • Supports Sprockets 4.x, 3.x, 2.x
  • Lets you use JSX, ES6, TypeScript, CoffeeScript 

Get started with Webpacker

Alternatively, get started with Sprockets

Webpacker provides modern JS tooling for Rails. Here are the listed steps for integrating Webpacker and Rails-React with Rails:

1) Create a new Rails app:

$ rails new my-app
$ cd my-app

2) Add react-rails to your Gemfile:

gem 'react-rails'

Note: On rails versions < 6.0, You need to add gem 'webpacker' to your Gemfile in step 2 above.

3) Now run the installers:

Rails 6.x and 5.x:

$ bundle install
$ rails webpacker:install         # OR (on rails version < 5.0) rake webpacker:install
$ rails webpacker:install:react   # OR (on rails version < 5.0) rake webpacker:install:react
$ rails generate react:install

This gives you:

  • app/javascript/components/ directory for your React components
  • ReactRailsUJS setup in app/javascript/packs/application.js
  • app/javascript/packs/server_rendering.js for server-side rendering

Note: On rails versions < 6.0, link the JavaScript pack in Rails view using javascript_pack_tag helper:

<!-- application.html.erb in Head tag below turbolinks -->
<%= javascript_pack_tag 'application' %>

4) Generate your first component:

$ rails g react:component HelloWorld greeting:string

5) You can also generate your component in a subdirectory:

$ rails g react:component my_subdirectory/HelloWorld greeting:string

Note: Your component is added to app/javascript/components/ by default.

Note: If your component is in a subdirectory you will append the directory path to your erb component call.

Example:

<%= react_component("my_subdirectory/HelloWorld", { greeting: "Hello from react-rails." }) %>

6) Render it in a Rails view:

<!-- erb: paste this in view -->
<%= react_component("HelloWorld", { greeting: "Hello from react-rails." }) %>

7) Lets Start the app:

$ rails s

output: greeting: Hello from react-rails", inspect webpage in your browser too see change in tag props.

Component name

The component name tells react-rails where to load the component. For example:

react_component callcomponent require
react_component("Item")require("Item")
react_component("items/index")require("items/index")
react_component("items.Index")require("items").Index
react_component("items.Index.Header")require("items").Index.Header

This way, you can access top-level, default, or named exports.

The require.context inserted into packs/application.js is used to load components. If you want to load components from a different directory, override it by calling ReactRailsUJS.useContext:

var myCustomContext = require.context("custom_components", true)
var ReactRailsUJS = require("react_ujs")
// use `custom_components/` for <%= react_component(...) %> calls
ReactRailsUJS.useContext(myCustomContext)

If require fails to find your component, ReactRailsUJS falls back to the global namespace, described in Use with Asset Pipeline.

File naming

React-Rails supports plenty of file extensions such as: .js, .jsx.js, .js.jsx, .es6.js, .coffee, etcetera! Sometimes this will cause a stumble when searching for filenames.

Component File Namereact_component call
app/javascript/components/samplecomponent.jsreact_component("samplecomponent")
app/javascript/components/sample_component.jsreact_component("sample_component")
app/javascript/components/SampleComponent.jsreact_component("SampleComponent")
app/javascript/components/SampleComponent.js.jsxHas to be renamed to SampleComponent.jsx, then use react_component("SampleComponent")

Typescript support

If you want to use React-Rails with Typescript, simply run the installer and add @types:

$ bundle exec rails webpacker:install:typescript
$ yarn add @types/react @types/react-dom

Doing this will allow React-Rails to support the .tsx extension. Additionally, it is recommended to add ts and tsx to the server_renderer_extensions in your application configuration:

config.react.server_renderer_extensions = ["jsx", "js", "tsx", "ts"]

Test component

You can use assert_react_component to test component render:

app/views/welcome/index.html.erb
<%= react_component("HelloWorld", { greeting: "Hello from react-rails.", info: { name: "react-rails" } }, { class: "hello-world" }) %>
class WelcomeControllerTest < ActionDispatch::IntegrationTest
  test 'assert_react_component' do
    get "/welcome"
    assert_equal 200, response.status

    # assert rendered react component and check the props
    assert_react_component "HelloWorld" do |props|
      assert_equal "Hello from react-rails.", props[:greeting]
      assert_equal "react-rails", props[:info][:name]
      assert_select "[class=?]", "hello-world"
    end

    # or just assert component rendered
    assert_react_component "HelloWorld"
  end
end

Use with Asset Pipeline

react-rails provides a pre-bundled React.js & a UJS driver to the Rails asset pipeline. Get started by adding the react-rails gem:

gem 'react-rails'

And then install the react generator:

$ rails g react:install

Then restart your development server.

This will:

  • add some //= requires to application.js
  • add a components/ directory for React components
  • add server_rendering.js for server-side rendering

Now, you can create React components in .jsx files:

// app/assets/javascripts/components/post.jsx

window.Post = createReactClass({
  render: function() {
    return <h1>{this.props.title}</h1>
  }
})

// or, equivalent:
class Post extends React.Component {
  render() {
    return <h1>{this.props.title}</h1>
  }
}

Then, you can render those components in views:

<%= react_component("Post", {title: "Hello World"}) %>

Components must be accessible from the top level, but they may be namespaced, for example:

<%= react_component("Comments.NewForm", {post_id: @post.id}) %>
<!-- looks for `window.Comments.NewForm` -->

Custom JSX Transformer

react-rails uses a transformer class to transform JSX in the asset pipeline. The transformer is initialized once, at boot. You can provide a custom transformer to config.react.jsx_transformer_class. The transformer must implement:

  • #initialize(options), where options is the value passed to config.react.jsx_transform_options
  • #transform(code_string) to return a string of transformed code

react-rails provides two transformers, React::JSX::BabelTransformer (which uses ruby-babel-transpiler) and React::JSX::JSXTransformer (which uses the deprecated JSXTransformer.js).

Transform Plugin Options

To supply additional transform plugins to your JSX Transformer, assign them to config.react.jsx_transform_options

react-rails uses the Babel version of the babel-source gem.

For example, to use babel-plugin-transform-class-properties :

config.react.jsx_transform_options = {
  optional: ['es7.classProperties']
}

React.js versions

//= require react brings React into your project.

By default, React's [development version] is provided to Rails.env.development. You can override the React build with a config:

# Here are the defaults:
# config/environments/development.rb
MyApp::Application.configure do
  config.react.variant = :development
end

# config/environments/production.rb
MyApp::Application.configure do
  config.react.variant = :production
end

Be sure to restart your Rails server after changing these files. See VERSIONS.md to learn which version of React.js is included with your react-rails version. In some edge cases you may need to bust the sprockets cache with rake tmp:clear

View Helper

react-rails includes a view helper and an unobtrusive JavaScript driver which work together to put React components on the page.

The view helper (react_component) puts a div on the page with the requested component class & props. For example:

<%= react_component('HelloMessage', name: 'John') %>
<!-- becomes: -->
<div data-react-class="HelloMessage" data-react-props="{&quot;name&quot;:&quot;John&quot;}"></div>

On page load, the react_ujs driver will scan the page and mount components using data-react-class and data-react-props.

The view helper's signature is:

react_component(component_class_name, props={}, html_options={})
  • component_class_name is a string which identifies a component. See getConstructor for details.
  • props is either:
    • an object that responds to #to_json; or
    • an already-stringified JSON object (see JBuilder note below).
  • html_options may include:
    • tag: to use an element other than a div to embed data-react-class and data-react-props.
    • prerender: true to render the component on the server.
    • camelize_props to transform a props hash
    • **other Any other arguments (eg class:, id:) are passed through to content_tag.

Custom View Helper

react-rails uses a "helper implementation" class to generate the output of the react_component helper. The helper is initialized once per request and used for each react_component call during that request. You can provide a custom helper class to config.react.view_helper_implementation. The class must implement:

  • #react_component(name, props = {}, options = {}, &block) to return a string to inject into the Rails view
  • #setup(controller_instance), called when the helper is initialized at the start of the request
  • #teardown(controller_instance), called at the end of the request

react-rails provides one implementation, React::Rails::ComponentMount.

UJS

react-rails's JavaScript is available as "react_ujs" in the asset pipeline or from NPM. It attaches itself to the window as ReactRailsUJS.

Mounting & Unmounting

Usually, react-rails mounts & unmounts components automatically as described in Event Handling below.

You can also mount & unmount components from <%= react_component(...) %> tags using UJS:

// Mount all components on the page:
ReactRailsUJS.mountComponents()
// Mount components within a selector:
ReactRailsUJS.mountComponents(".my-class")
// Mount components within a specific node:
ReactRailsUJS.mountComponents(specificDOMnode)

// Unmounting works the same way:
ReactRailsUJS.unmountComponents()
ReactRailsUJS.unmountComponents(".my-class")
ReactRailsUJS.unmountComponents(specificDOMnode)

You can use this when the DOM is modified by AJAX calls or modal windows.

Event Handling

ReactRailsUJS checks for various libraries to support their page change events:

  • Turbolinks
  • pjax
  • jQuery
  • Native DOM events

ReactRailsUJS will automatically mount components on <%= react_component(...) %> tags and unmount them when appropriate.

If you need to re-detect events, you can call detectEvents:

// Remove previous event handlers and add new ones:
ReactRailsUJS.detectEvents()

For example, if Turbolinks is loaded after ReactRailsUJS, you'll need to call this again. This function removes previous handlers before adding new ones, so it's safe to call as often as needed.

If Turbolinks is imported via Webpacker (and thus not available globally), ReactRailsUJS will be unable to locate it. To fix this, you can temporarily add it to the global namespace:

// Order is particular. First start Turbolinks:
Turbolinks.start();
// Add Turbolinks to the global namespace:
window.Turbolinks = Turbolinks;
// Remove previous event handlers and add new ones:
ReactRailsUJS.detectEvents();
// (Optional) Clean up global namespace:
delete window.Turbolinks;

getConstructor

Components are loaded with ReactRailsUJS.getConstructor(className). This function has two built-in implementations:

  • On the asset pipeline, it looks up className in the global namespace.
  • On Webpacker, it requires files and accesses named exports, as described in Get started with Webpacker.

You can override this function to customize the mapping of name-to-constructor. Server-side rendering also uses this function.

Server-Side Rendering

You can render React components inside your Rails server with prerender: true:

<%= react_component('HelloMessage', {name: 'John'}, {prerender: true}) %>
<!-- becomes: -->
<div data-react-class="HelloMessage" data-react-props="{&quot;name&quot;:&quot;John&quot;}">
  <h1>Hello, John!</h1>
</div>

(It will also be mounted by the UJS on page load.)

Server rendering is powered by ExecJS and subject to some requirements:

  • react-rails must load your code. By convention, it uses server_rendering.js, which was created by the install task. This file must include your components and their dependencies (eg, Underscore.js).
  • Your code can't reference document or window. Prerender processes don't have access to document or window, so jQuery and some other libs won't work in this environment :(

ExecJS supports many backends. CRuby users will get the best performance from mini_racer.

Configuration

Server renderers are stored in a pool and reused between requests. Threaded Rubies (eg jRuby) may see a benefit to increasing the pool size beyond the default 0.

These are the default configurations:

# config/application.rb
# These are the defaults if you don't specify any yourself
module MyApp
  class Application < Rails::Application
    # Settings for the pool of renderers:
    config.react.server_renderer_pool_size  ||= 1  # ExecJS doesn't allow more than one on MRI
    config.react.server_renderer_timeout    ||= 20 # seconds
    config.react.server_renderer = React::ServerRendering::BundleRenderer
    config.react.server_renderer_options = {
      files: ["server_rendering.js"],       # files to load for prerendering
      replay_console: true,                 # if true, console.* will be replayed client-side
    }
    # Changing files matching these dirs/exts will cause the server renderer to reload:
    config.react.server_renderer_extensions = ["jsx", "js"]
    config.react.server_renderer_directories = ["/app/assets/javascripts", "/app/javascript/"]
  end
end

JavaScript State

Some of ExecJS's backends are stateful (eg, mini_racer, therubyracer). This means that any side-effects of a prerender will affect later renders with that renderer.

To manage state, you have a couple options:

  • Make a custom renderer with #before_render / #after_render hooks as described below
  • Use per_request_react_rails_prerenderer to manage state for a whole controller action.

To check out a renderer for the duration of a controller action, call the per_request_react_rails_prerenderer helper in the controller class:

class PagesController < ApplicationController
  # Use the same React server renderer for the entire request:
  per_request_react_rails_prerenderer
end

Then, you can access the ExecJS context directly with react_rails_prerenderer.context:

def show
  react_rails_prerenderer           # => #<React::ServerRendering::BundleRenderer>
  react_rails_prerenderer.context   # => #<ExecJS::Context>

  # Execute arbitrary JavaScript code
  # `self` is the global context
  react_rails_prerenderer.context.exec("self.Store.setup()")
  render :show
  react_rails_prerenderer.context.exec("self.Store.teardown()")
end

react_rails_prerenderer may also be accessed in before- or after-actions.

Custom Server Renderer

react-rails depends on a renderer class for rendering components on the server. You can provide a custom renderer class to config.react.server_renderer. The class must implement:

  • #initialize(options={}), which accepts the hash from config.react.server_renderer_options
  • #render(component_name, props, prerender_options) to return a string of HTML

react-rails provides two renderer classes: React::ServerRendering::ExecJSRenderer and React::ServerRendering::BundleRenderer.

ExecJSRenderer offers two other points for extension:

  • #before_render(component_name, props, prerender_options) to return a string of JavaScript to execute before calling React.render
  • #after_render(component_name, props, prerender_options) to return a string of JavaScript to execute after calling React.render

Any subclass of ExecJSRenderer may use those hooks (for example, BundleRenderer uses them to handle console.* on the server).

Controller Actions

Components can also be server-rendered directly from a controller action with the custom component renderer. For example:

class TodoController < ApplicationController
  def index
    @todos = Todo.all
    render component: 'TodoList', props: { todos: @todos }, tag: 'span', class: 'todo'
  end
end

You can also provide the "usual" render arguments: content_type, layout, location and status. By default, your current layout will be used and the component, rather than a view, will be rendered in place of yield. Custom data-* attributes can be passed like data: {remote: true}.

Prerendering is set to true by default, but can be turned off with prerender: false.

Component Generator

You can generate a new component file with:

rails g react:component ComponentName prop1:type prop2:type ...

For example,

rails g react:component Post title:string published:bool published_by:instanceOf{Person}

would generate:

var Post = createReactClass({
  propTypes: {
    title: PropTypes.string,
    published: PropTypes.bool,
    publishedBy: PropTypes.instanceOf(Person)
  },

  render: function() {
    return (
      <React.Fragment>
        Title: {this.props.title}
        Published: {this.props.published}
        Published By: {this.props.publishedBy}
      </React.Fragment>
    );
  }
});

The generator also accepts options:

  • --es6: use class ComponentName extends React.Component
  • --coffee: use CoffeeScript

Accepted PropTypes are:

  • Plain types: any, array, bool, element, func, number, object, node, shape, string
  • instanceOf takes an optional class name in the form of instanceOf{className}.
  • oneOf behaves like an enum, and takes an optional list of strings in the form of 'name:oneOf{one,two,three}'.
  • oneOfType takes an optional list of react and custom types in the form of 'model:oneOfType{string,number,OtherType}'.

Note that the arguments for oneOf and oneOfType must be enclosed in single quotes to prevent your terminal from expanding them into an argument list.

Use with JBuilder

If you use Jbuilder to pass a JSON string to react_component, make sure your JSON is a stringified hash, not an array. This is not the Rails default -- you should add the root node yourself. For example:

# BAD: returns a stringified array
json.array!(@messages) do |message|
  json.extract! message, :id, :name
  json.url message_url(message, format: :json)
end

# GOOD: returns a stringified hash
json.messages(@messages) do |message|
  json.extract! message, :id, :name
  json.url message_url(message, format: :json)
end

Camelize Props

You can configure camelize_props option:

MyApp::Application.configure do
  config.react.camelize_props = true # default false
end

Now, Ruby hashes given to react_component(...) as props will have their keys transformed from underscore- to camel-case, for example:

{ all_todos: @todos, current_status: @status }
# becomes:
{ "allTodos" => @todos, "currentStatus" => @status }

You can also specify this option in react_component:

<%= react_component('HelloMessage', {name: 'John'}, {camelize_props: true}) %>

Upgrading

2.3 to 2.4

Keep your react_ujs up to date, yarn upgrade

React-Rails 2.4.x uses React 16+ which no longer has React Addons. Therefore the pre-bundled version of react no longer has an addons version, if you need addons still, there is the 2.3.1+ version of the gem that still has addons.

If you need to make changes in your components for the prebundled react, see the migration docs here:

For the vast majority of cases this will get you most of the migration:

  • global find+replace React.Prop -> Prop
  • add import PropTypes from 'prop-types' (Webpacker only)
  • re-run bundle exec rails webpacker:install:react to update npm packages (Webpacker only)

Common Errors

During installation

  1. While using installers.(rails webpacker:install:react && rails webpacker:install) Error:
public/packs/manifest.json. Possible causes:
1. You want to set webpacker.yml value of compile to true for your environment
   unless you are using the `webpack -w` or the webpack-dev-server.
2. webpack has not yet re-run to reflect updates.
3. You have misconfigured Webpacker's config/webpacker.yml file.
4. Your webpack configuration is not creating a manifest.
or
yarn: error: no such option: --dev
ERROR: [Errno 2] No such file or directory: 'add'

Fix: Try updating yarn package.

sudo apt remove cmdtest
sudo apt remove yarn
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get update && sudo apt-get install yarn

yarn install

Undefined Set

ExecJS::ProgramError (identifier 'Set' undefined):

(execjs):1

If you see any variation of this issue, see Using TheRubyRacer

Using TheRubyRacer

TheRubyRacer hasn't updated LibV8 (The library that powers Node.js) from v3 in 2 years, any new features are unlikely to work.

LibV8 itself is already beyond version 7 therefore many serverside issues are caused by old JS engines and fixed by using an up to date one such as MiniRacer or TheRubyRhino on JRuby.

HMR

Hot Module Replacement is possible with this gem as it does just pass through to Webpacker. Please open an issue to let us know tips and tricks for it to add to the wiki.

Sample repo that shows HMR working with react-rails: https://github.com/edelgado/react-rails-hmr

One caveat is that currently you cannot Server-Side Render along with HMR.

Related Projects

Contributing

🎉 Thanks for taking the time to contribute! 🎉

With 5 Million+ downloads of the react-rails Gem and another 2 Million+ downloads of react_ujs on NPM, you're helping the biggest React + Rails community!

By contributing to React-Rails, you agree to abide by the code of conduct.

You can always help by submitting patches or triaging issues, even offering reproduction steps to issues is incredibly helpful!

Please see our Contribution guide for more info.

A source code example utilizing React-Rails: https://github.com/BookOfGreg/react-rails-example-app

Author: Reactjs
Source Code: https://github.com/reactjs/react-rails 
License: Apache-2.0 license

#react #javascript #typescript #ruby #rails 

React-rails: integrate React.js with Rails Views and Controllers

Make Your own real Clock Widget Application using python

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
##    clockWidget = QtWidgets.QWidget()
    ui = Ui_clockWidget()
##    ui.setupUi(clockWidget)
    ui.show()
    sys.exit(app.exec_())

Make your own Clock Widget for your computer using python.

and convert into real application.

Full Course of app development step by step is described here.

Watch Full Course

The app will be installed in your computer program files. and can uninstall it easily. ClockWidget app will run automatically when your system starts. and many features are there. watch full course series to learn.

First on Net

#python #app #development #exe #setup_file #pyqt5 #pyside2 #qtdesigner #innosetup

Talia  Lowe

Talia Lowe

1635281296

Setup Next.js Project for WooCommerce React Application

Chapter One: In this tutorial, we will learn to Setup Nextjs React Application For WooCommerce REST API Project.

#react  #woocommerce  #setup 

 Setup Next.js Project for WooCommerce React Application
Lenna  Kihn

Lenna Kihn

1634846400

Instructions For Setting Up Wireguard on Linux

We look into how to set up WireGuard on a Linux system. In this case, we use Debian in order to create a tunnel between two nodes using WireGuard. The setup is quite easy because WireGuard has strong opinions about what should be available and that means that the setup doesn't have that many things to configure.

#linux  #wireguard  #setup 

Instructions For Setting Up Wireguard on Linux
Jackson  Watson

Jackson Watson

1625638740

Setup Your First Server, Right Now (and Get $100 Or 60 Days Free) - Beyond Code Live 005

How to set up your own server, in the simplest way possible - using Digital Ocean and Caddy.
Digital Ocean ($100 or 60 days Free): https://m.do.co/c/18ec10e74dae
Name.com Domains: https://www.name.com/referral/13d0ac

Follow Beyond Code:(Learn to Code in 15 Minutes a Day)
Facebook: https://www.facebook.com/beyondcodebootcamp
YouTube: https://www.youtube.com/channel/UC2KJHARTj6KRpKzLU1sVxBA
Twitter: https://twitter.com/_beyondcode

Follow Health, Wealth, Commitment
(Daily Lifestyle Chat)
Facebook: https://www.facebook.com/groups/5406824179391158
YouTube: https://www.youtube.com/channel/UCbw2SbqD0OofAEVF_T61wCQ

#server #setup #setup your first server #caddy #digital ocean

Setup Your First Server, Right Now (and Get $100 Or 60 Days Free) - Beyond Code Live 005
Eliseo  Kutch

Eliseo Kutch

1625130180

React JS Tutorial - 1 - Setup

In this tutorial, we learn how to setup react js environment on the local computer and start development.

Useful Links:
Node JS Download: https://nodejs.org/en/

#react js #react #setup

React JS Tutorial - 1 - Setup

mix router

1623482721

Linksys Velop Login | Linksys Velop Setup App | Linksys Velop Setup

If you have any Linksys Velop Connection Issues, then this article will help you to solve Linksys Velop Connection Issues. Linksys Velop Connection Issues The wireless router’s signal is weak. The router’s firmware has to be updated. Wireless devices in the surroundings produce interference. If you want more solutions for Linksys Velop Connection Issues you can visit our site and get more knowledge about Linksys Velop Connection Issues.

#linksys #velop #setup #login #linksysvelopappsetup #linksysvelopconnection

Linksys Velop Login | Linksys Velop Setup App | Linksys Velop Setup

nest setup

1623476824

nest camera login | nest camera setup | nest camera login issues

If you are unable to solve the Nest Camera Login Issues so don’t worry, The most common issues include being unable to load the nest camera login page and being unable to connect to the internet. Check to see if your gadgets are correctly linked, and if not, try disconnecting and reconnecting them. You can double-check that you’re typing the correct site address and that your browser isn’t acting up. Otherwise, you’ll have to switch browsers. If you are still facing the problem of Nest Camera Login Issues then you can visit our site.

#nestcameralogin #nest #camera #setup #login #nestcamerasetup

nest camera login | nest camera setup | nest camera login issues
Aaron Schmidt

Aaron Schmidt

1621969536

Office.com/setup | Office Aktivieren in Windows

Installieren Sie Ihr Office Program in WINDOWS von office.com/setup in folgenden Schritten:

Schritt 1 – Melden Sie sich an, um Office zu herunterladen

Gehen Sie zu office.com/setup und wählen Sie Anmelden, wenn Sie noch nicht angemeldet sind.

Melden Sie sich mit dem Konto an, das Sie dieser Office-Version zugeordnet haben. Dieses Konto kann ein MS-Konto oder ein Arbeits- oder Schulkonto sein.

Befolgen Sie nach der Anmeldung die Schritte, die dem Kontotyp entsprechen, mit dem Sie sich angemeldet haben.

Wählen Sie auf der Office-Startseite die Option Office installieren.

Wählen Sie Installieren (oder abhängig von Ihrer Version Office installieren>).

Damit beginnt der Download von Office. Befolgen Sie die Anweisungen auf Ihrem Bildschirm, um die Installation abzuschließen.

Schritt 2 – Office installieren

Klicken Sie je nach Browser auf Ausführen (in MS Edge oder Internet Explorer), Setup (in Chrome) oder Datei speichern (in Firefox).

Wenn die Eingabeaufforderung zur Benutzerkontensteuerung angezeigt wird, die besagt: Möchten Sie dieser App erlauben, Änderungen an Ihrem Gerät vorzunehmen? Klicken Sie auf Ja.

Ihre Installation ist abgeschlossen, wenn Sie den Satz “Sie sind fertig! Office ist jetzt installiert” sehen und eine Animation abgespielt wird, die Ihnen zeigt, wo Sie Office-Anwendungen auf Ihrem Computer finden.

Befolgen Sie beispielsweise die Anweisungen im Fenster. Klicken Sie auf Start> Alle Apps, um zu sehen, wo sich Ihre Apps befinden, und wählen Sie Schließen.

Schritt 3: Office aktivieren

Verwenden Sie sofort eine Office-Anwendung, indem Sie eine App wie Word oder Excel öffnen. In den meisten Fällen wird Office aktiviert, sobald Sie eine Anwendung starten und nachdem Sie auf Akzeptieren geklickt haben, um den Lizenzbedingungen zuzustimmen.

Office wird möglicherweise automatisch aktiviert.

Abhängig von Ihrem Produkt wird möglicherweise der MS Office-Aktivierungsassistent angezeigt. Befolgen Sie in diesem Fall die Anweisungen zum Aktivieren von Office.

Visit - office.com/setup und aktivieren Sie Ihr Office Setup

#office.com/setup #office setup #setup.office.com #www.office.com/setup

#officesetup #office.com/setup #www.office.com #setup.office.com

Office.com/setup | Office Aktivieren in Windows

nest setup

1619857535

Nest camera setup | Nest camera login | nest camera wifi settings

Nest camera is used as a security purpose from the burglars and the intruders who have an eye on your home. In order to use Nest Camera, users have to create an account for nest camera login. while there are most of user accessing the error when they login in nest camera if you are one of them, then don’t worry you can visit our site to solve the error of nest camera login process, nest outdoor camera not connecting, nest camera setup on computer and find another useful tips which is beneficial for your further login process.

#nestcameralogin #nestoutdoorcameranotconnecting #nestcamerasetup #nest #camera #setup

Nest camera setup | Nest camera login | nest camera wifi settings

How to setup Node/Express development environment » grokonez

https://grokonez.com/node-js/how-to-setup-node-express-development-environment

How to setup Node/Express development environment

In the tutorial, we will show you how to setup Node/Express development environment that includes installation of Nodejs, NPM package, and ‘Express Application Generator’ optionally.

Installing Node

- Go to: https://nodejs.org/en/ - Download the LTS build that is "Recommended for most users" download nodejs - LTS version

Double-clicking on the downloaded file and following the installation prompts:

install nodejs

Testing your Nodejs and NPM installation:


>node -v
v8.11.1

>npm -v
5.6.0

Create a ‘helloworld.js’, use ‘http’ module to create a Nodejs server createServer().


//Load HTTP module
var http = require("http");

//Create HTTP server and listen on port 8000 for requests
http.createServer(function (request, response) {

   // Set the response HTTP header with HTTP status and Content type
   response.writeHead(200, {'Content-Type': 'text/plain'});
   
   // Send the response body "Hello World"
   response.end('Hello World\n');
}).listen(8000);

// Print URL for accessing server
console.log('Server running at http://127.0.0.1:8000/')

Start the server:

More at:

https://grokonez.com/node-js/how-to-setup-node-express-development-environment

#node #express #setup #development

How to setup Node/Express development environment » grokonez