Go to content
The Codest
  • About Us
    • Staff Augmentation
    • Project Development
    • Cloud Engineering
    • Quality Assurance
    • Web Development
  • Our Team
  • Case studies
    • Blog
    • Meetups
    • Webinars
    • Resources
Careers Get in touch
  • About Us
    • Staff Augmentation
    • Project Development
    • Cloud Engineering
    • Quality Assurance
    • Web Development
  • Our Team
  • Case studies
    • Blog
    • Meetups
    • Webinars
    • Resources
Careers Get in touch
2021-06-22
Software Development

StimulusReflex – a quick way to create reactive apps

Pawel Muszynski

Software Engineer

StimulusReflex – a quick way to create reactive apps  - Image

What is StimulusReflex? Quite popular nowadays HTML over-the-wire approach led us to the creation of frameworks and libraries which send HTML over the wire instead of using JSON. StimulusReflex is one of them.

It is new way to create reactive user interface in Ruby on Rails. StimulusReflex extends the capabilities of Rails and Stimulus by capturing user interactions and passing them to Rails over real-time websockets. Pages are quickly re-rendered and all updates are sent to the client via CableReady.

CableReady allows to create real-time updates by triggering client-side DOM changes, events and notifications via ActionCable. Unlike Ajax, operations are not always initiated by the user other browser, for example, they can also be initiated by workers.

StimulusReflex was originally inspired by Phoenix’s LiveView (an alternative to the SPA). StimulusReflex’s goal has always been to make building modern apps with Rails the most productive and enjoyable option available. And in my opinion, this is exactly what they achieved here.

Why should we use StimulusReflex?

It’s simple, to focus on developing a product instead of introducing consistent changes in modern JavaScript. Also, StimulusReflex applications have simple, concise and clear code and integrate seamlessly with Ruby on Rails. This allows small RoR teams to do big things even without great knowledge of React, Vue or their modern JavaScript solutions.

How does StimulusReflex works?

Reflex

Reflex is a transactional UI update that takes place over a persistent open connection to the server. StimulusReflex maps requests to Reflex class. Reflex classes are in the app/reflexes directory.

class PostReflex < ApplicationReflex
end

If we create Reflex class with a generator, we can see that our class contains this comment:

 # All Reflex instances include CableReady::Broadcaster and expose the following properties:
 #
 #   - connection – the ActionCable connection,
 #   - channel – the ActionCable channel,
 #   - request – an ActionDispatch::Request proxy for the socket connection,
 #   - session – the ActionDispatch::Session store for the current visitor,
 #   - flash – the ActionDispatch::Flash::FlashHash for the current request,
 #   - url – the URL of the page that triggered the reflex,
 #   - params – parameters from the element’s closest form (if any),
 #   - element – a Hash-like object that represents the HTML element that triggered the reflex,
 #     - signed – uses a signed Global ID to map dataset attributed to a model e.g., element.signed[:foo],
 #     - unsigned – uses an unsigned Global ID to map dataset attributed to a model e.g., element.unsigned[:foo],
 #   - cable_ready – a special cable_ready that can broadcast to the current visitor (no brackets needed),
 #   - reflex_id – a UUIDv4 that uniquely identifies each Reflex.

As we can see, there are few properties that can be used in our class. The most interesting at the beginning will be the element property that contains all of the Stimulus controller’s DOM element attributes as well as other properties, like tagName, checked and value.

StimulusReflex also gives us a set of callbacks to allow us to control our reflex’s processes:

  • before_reflex
  • around_reflex
  • after_reflex

As you can see, the naming is very similar to Active Record Callbacks.

Declaring a Reflex in HTML with data attribute

The fastest way to enable Reflex actions is by using the data-reflex attribute. The syntax follows the Stimulus format: [DOM-event]->[ReflexClass]#[action]

<button
 data-reflex="click->Post#increment"
 data-post-id="<%= post.id %>"
>Like</button>

In this example, the data-reflex attribute pointed out the PostRefex class and the increment method on the click event. Here we also passed data-post-id that we can later use in the Reflex class through element.dataset[:post_id].

class PostsReflex < ApplicationReflex
 def increment
   post = Post.find(element.dataset[:post_id])

   post.increment! :likes
 end
end

Morphs

By default, StimulusReflex updates the entire page (Page morph). After re-processing the controller action, rendering the view template and sending the raw HTML to your browser, StimulusReflex uses the morphdom library to do the smallest number of DOM modifications necessary to refresh your UI in just a few milliseconds.

StimulusReflex features three distinct modes of operation:

Page Morph – performs a full-page update, Selector Morph – replaces the content of an element, Nothing Morph – executes functions that do not update your page (for example, calling your employee).

To change our PostReflex#increment method, we can simply use the morph keyword and target the partial that we want to update.

def increment
 post = Post.find(element.dataset[:post_id])
 post.increment! :likes

 morph "#posts_#{post.id}", render(partial: 'post', locals: { posts: post })
end

My thoughts

This quite a short introduction is enough to start your journey with reactive Rails using StimulusReflex. Isn't it great to be able to create a reactive SPA app with just a few Ruby lines and no JavaScript? For me, this whole HTML over-the-wire idea is exciting, and I will definitely dig into this topic in the future. For now, I highly recommend to you StimulusReflex documentation. Shoutout to all people involved into the development of StimulusReflex!

Read more:

Why you should (probably) use Typescript

How not to kill a project with bad coding practices?

Data fetching strategies in NextJS

Related articles

Software Development

3 Useful HTML Tags You Might Not Know Even Existed

Nowadays, accessibility (A11y) is crucial on all stages of building custom software products. Starting from the UX/UI design part, it trespasses into advanced levels of building features in code. It provides tons of benefits for...

Jacek Ludzik
Software Development

5 examples of Ruby’s best usage

Have you ever wondered what we can do with Ruby? Well, the sky is probably the limit, but we are happy to talk about some more or less known cases where we can use this powerful language. Let me give you some examples.

Pawel Muszynski
Software Development

Maintaining a Project in PHP: 5 Mistakes to Avoid

More than one article has been written about the mistakes made during the process of running a project, but rarely does one look at the project requirements and manage the risks given the technology chosen.

Sebastian Luczak
Software Development

Why you will find qualified Ruby developers in Poland?

Real Ruby professionals are rare birds on the market. Ruby is not the most popular technology, so companies often struggle with the problem of finding developers who have both high-level skills and deep experience; oh, and by the...

Jakub
Software Development

9 Mistakes to Avoid While Programming in Java

What mistakes should be avoided while programming in Java? In the following piece we answers this question.

Rafal Sawicki
Software Development

A quick dive into Ruby 2.6. What is new?

Released quite recently, Ruby 2.6 brings a bunch of conveniences that may be worth taking a glimpse of.  What is new? Let’s give it a shot!

Patrycja Slabosz

Subscribe to our knowledge base and stay up to date on the expertise from industry.

About us

The Codest – International Tech Software Company with tech hubs in Poland.

    United Kingdom - Headquarters

  • Office 303B, 182-184 High Street North E6 2JA London, England

    Poland - Local Tech Hubs

  • Business Link High5ive, Pawia 9, 31-154 Kraków, Poland
  • Brain Embassy, Konstruktorska 11, 02-673 Warsaw, Poland

    The Codest

  • Home
  • About us
  • Services
  • Case studies
  • Know how
  • Careers

    Services

  • PHP development
  • Java development
  • Python development
  • Ruby on Rails development
  • React Developers
  • Vue Developers
  • TypeScript Developers
  • DevOps
  • QA Engineers

    Resources

  • What are top CTOs and CIOs Challenges? [2022 updated]
  • Facts and Myths about Cooperating with External Software Development Partner
  • From the USA to Europe: Why do American startups decide to relocate to Europe
  • Privacy policy
  • Website terms of use

Copyright © 2022 by The Codest. All rights reserved.

We use cookies on the site for marketing, analytical and statistical purposes. By continuing to use, without changing your privacy settings, our site, you consent to the storage of cookies in your browser. You can always change the cookie settings in your browser. You can find more information in our Privacy Policy.