Code Monkey home page Code Monkey logo

optimism's Introduction

Optimism

GitHub stars GitHub forks Twitter follow Discord

The missing drop-in solution for realtime remote form validation in Rails.

{% hint style="success" %} Optimism v0.4.1 now supports Ruby 3.0.0, thanks to Julian Rubisch and Rails 6.1, thanks to Josh LeBlanc. 🎉 {% endhint %}

Why have optimism?

Optimism is an MIT-licensed Ruby on Rails gem that makes it easy to give your users instant constructive feedback if they enter invalid data into your application. Instead of dumping a list of errors at the top of your interface, Optimism provides specific instructions directly beside or below individual input elements.

You can try a 👉 live demo 👈 right now.

Is optimism for you?

Are you trying to use remote forms but feeling frustrated by their inflexibility? You need to mainline a dose of Optimism, stat!

If you care about reducing churn and giving your users the best experience possible, Optimism is a great way to achieve your UX goals without having to waste time writing repetitive and brittle validation code. Properly constrained and highly opinionated, you'll be able to keep your validation logic on the server where it belongs without sacrificing the immediate response of a reactive Single Page App. Whether you're working on a complex multi-element form with a traditional Submit button or a dynamic search that delivers results as you type, Optimism chops, grinds, slices and dices your validation concerns away.

Optimism is safe and approved for all diets, religions and political appetites. Many developers find that Optimism is highly addictive and lowers stress when applied regularly.

How does optimism work?

Rails applications receive requests to update database records based on a list of proposed changes that come from a dog user submitting a form in their browser. If all proposed changes can be made without breaking any business rules, ActiveRecord can update the email address and age of the dog user. Optimism kicks in when user_params = {email: 7, age: "[email protected]"}.

When a model validation error prevents an update from succeeding, Optimism builds a list of issues that must be resolved. This list is broadcast to the browser over a websocket connection, and the live document is changed to show the necessary validation hints. No page refreshes are required and the entire process happens faster than you can blink.

Key features and advantages

  • Easy to learn, quick to implement
  • Automatically handles multi-level nested forms
  • Plays well with existing tools such as StimulusReflex, Turbolinks and even jQuery
  • Contextual user feedback in a few milliseconds
  • Supports form-based and in-line edit scenarios equally well
  • Optional support for emitting DOM events
  • Highly configurable via an optional initializer file
  • CSS framework agnostic with Bootstrap and vanilla samples provided
  • Lightweight, coming in at ~100 LOC

Try it now

The project repository lives on Github at https://github.com/leastbad/optimism and this documentation is available at https://optimism.leastbad.com

There's a live demo that you can try right now at https://optimism-demo.herokuapp.com

Even better, the source code for the demo is available on Github. The project README lists every step required to build the demo application from scratch in about five minutes.

Excited? Great! Let's setup Optimism in your Rails application now. And if you're having any trouble at all, drop by our Discord server for help.

optimism's People

Contributors

aandrieu avatar andrewmcodes avatar andryusha avatar dependabot[bot] avatar gathuku avatar joshleblanc avatar julianrubisch avatar leastbad avatar pulgamecanica avatar toproupi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

optimism's Issues

Reactive validations

Hi @leastbad,

I've read the chapter on reactive validations with Optimism and, while I understand most of it, I'm having a little trouble understanding how to implement them. Do you have any examples to point out? Thank you in advance!

David

Usage with simple_form and bootstrap

Has anyone had success getting Optimism hooked up to Simple Form? It'd be awesome to generate the necessary markup automatically in the form builder.

Specs

@leastbad

I hope you are doing well.

I have found a small lull in my day-to-days and have a little time to spare.

If you were to pursue some initial specs, what would you prefer to use? MiniTest? Would you be interested in a specs-only PR?

maybe *$stdout*... is more accurate

$stderr.puts "=> #{channel[:app_path]} created"

....
I just wanted to point out that it might be more accurate to use $stdout... Im just a noob and I know it doesn't changes any functionality... haha I was just having a look at the cool Ruby files.
I will delete this issue soon because it's not an issue..... haha I just felt like sharing this....

Use it on devise forms

Hi guys!

How can I use it on devise new session form (sign in)?
Do I have to override session controller?
If so, what do I have to do there?
And about the view?

optimism:form:valid event does not fire

Im unsure how optimism:form:valid is intended to fire when broadcast_errors is only called in the controller when the resource is invalid, as per the documentation

#some controller 
    if resource.valid?
      #valid op
    else
      broadcast_errors resource, resource_params
    end
//some stimulus controller
document.addEventListener('optimism:form:valid', () => this.someEvent())
document.addEventListener('optimism:form:invalid', () => this.someEvent())

With a valid resource
Expected optimism:form:valid broadcast
Actual does not broadcast
With an invalid resource
Expected optimism:form:invalid broadcast
Actual == Expected

However, if I place broadcast_errors outside the valid? conditional and allow it to do its own model.valid? as per the code it does fire the event

#some controller 
    if resource.valid?
      #valid op
    else
      #noop
    end
    broadcast_errors resource, resource_params

With a valid resource
Expected optimism:form:valid broadcast
Actual == Expected

Does Optimism support broadcast_errors for both valid and invalid paths? How otherwise is form:valid expected to be emitted and consumed?

use model.erorrs.any? instead of model.invalid?

https://github.com/leastbad/optimism/blob/master/lib/optimism.rb#L73

before

  Post Exists? (0.2ms)  SELECT 1 AS one FROM "posts" WHERE "posts"."name" = ? AND "posts"."id" != ? LIMIT ?  [["name", "222"], ["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/posts_controller.rb:59:in `block (2 levels) in update'
  CACHE Post Exists? (0.0ms)  SELECT 1 AS one FROM "posts" WHERE "posts"."name" = ? AND "posts"."id" != ? LIMIT ?  [["name", "222"], ["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/posts_controller.rb:59:in `block (2 levels) in update'
  CACHE Post Exists? (0.0ms)  SELECT 1 AS one FROM "posts" WHERE "posts"."name" = ? AND "posts"."id" != ? LIMIT ?  [["name", "222"], ["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/posts_controller.rb:59:in `block (2 levels) in update'
  CACHE Post Exists? (0.0ms)  SELECT 1 AS one FROM "posts" WHERE "posts"."name" = ? AND "posts"."id" != ? LIMIT ?  [["name", "222"], ["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/posts_controller.rb:59:in `block (2 levels) in update'
  CACHE Post Exists? (0.0ms)  SELECT 1 AS one FROM "posts" WHERE "posts"."name" = ? AND "posts"."id" != ? LIMIT ?  [["name", "222"], ["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/posts_controller.rb:59:in `block (2 levels) in update'
[ActionCable] Broadcasting to OptimismChannel: {"cableReady"=>true, "operations"=>{"addCssClass"=>[{"selector"=>"#post_age_container", "name"=>"error"}, {"selector"=>"#post_form", "name"=>"invalid"}], "removeCssClass"=>[{"selector"=>"#post_name_container", "name"=>"error"}, {"selector"=>"#post_body_container", "name"=>"error"}, {"selector"=>"#post_consent_container", "name"=>"error"}], "textContent"=>[{"selector"=>"#post_name_error", "text"=>""}, {"selector"=>"#post_age_error", "text"=>"Age must be greater than or equal to 18"}, {"selector"=>"#post_body_error", "text"=>""}, {"selector"=>"#post_consent_error", "text"=>""}]}}

after

  Post Exists? (0.2ms)  SELECT 1 AS one FROM "posts" WHERE "posts"."name" = ? AND "posts"."id" != ? LIMIT ?  [["name", "222"], ["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/posts_controller.rb:59:in `block (2 levels) in update'
[ActionCable] Broadcasting to OptimismChannel: {"cableReady"=>true, "operations"=>{"addCssClass"=>[{"selector"=>"#post_age_container", "name"=>"error"}, {"selector"=>"#post_form", "name"=>"invalid"}], "removeCssClass"=>[{"selector"=>"#post_name_container", "name"=>"error"}, {"selector"=>"#post_body_container", "name"=>"error"}, {"selector"=>"#post_consent_container", "name"=>"error"}], "textContent"=>[{"selector"=>"#post_name_error", "text"=>""}, {"selector"=>"#post_age_error", "text"=>"Age must be greater than or equal to 18"}, {"selector"=>"#post_body_error", "text"=>""}, {"selector"=>"#post_consent_error", "text"=>""}]}}

Error with Rails 6.1.0

After upgrading Rails to the new 6.1.0 version the (great) Optimism gem throws an error when you try to start the server.

The error states:
mattr_reader': module attributes should be defined directly on class, not singleton (TypeError)

Tracing the stacktrace I think the error happens in this piece of code inside the Optimism module:

class << self
    mattr_accessor :channel, :form_class, :error_class, :disable_submit, :suffix, :emit_events, :add_css, :inject_inline, :container_selector, :error_selector, :form_selector, :submit_selector
    self.channel = ->(context) { "OptimismChannel" }
    self.form_class = "invalid"
    self.error_class = "error"
    self.disable_submit = false
    self.suffix = ""
    self.emit_events = false
    self.add_css = true
    self.inject_inline = true
    self.container_selector = "#RESOURCE_ATTRIBUTE_container"
    self.error_selector = "#RESOURCE_ATTRIBUTE_error"
    self.form_selector = "#RESOURCE_form"
    self.submit_selector = "#RESOURCE_submit"
  end

Is it possible to move those accessors out of the singleton-class?

Demo dead

Hi - just wanted to point out that the demo doesn't seem to work. Nothing happens when filling in inputs.

Had to manually create the `channels` directories while installing

Thanks for sharing your code! I'll share a note: while installing I had to manually create the channels directories.

% rails optimism:install
rails aborted!
Errno::ENOENT: No such file or directory @ rb_sysopen - ./app/javascript/channels/optimism_channel.js
... bin/rails:9:in `<top (required)>'
... bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
Tasks: TOP => optimism:install
(See full trace by running task with --trace)
% mkdir app/javascript/channels
% rails optimism:install
=> app/javascript/channels/optimism_channel.js created
rails aborted!
Errno::ENOENT: No such file or directory @ rb_sysopen - ./app/channels/optimism_channel.rb
... bin/rails:9:in `<top (required)>'
... bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
Tasks: TOP => optimism:install
(See full trace by running task with --trace)

Thanks again!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.