📜 ⬆️ ⬇️

Hotkeys in Ruby on Rails applications

Fingers on the rails Mousetrap - javascript library that allows you to easily and easily add hotkeys to sites, appeared not so long ago. But I already managed to catch the fancy of me so much that I decided to make its addition to the Ruby on Rails project simple and enjoyable. Namely, wrap in a ruby ​​library for rails. This is how the gem mousetrap-rails appeared .


Connection


To use the library in a project, add a Gemfile your application's Gemfile .
 gem 'mousetrap-rails' 

and follow
 $ bundle install 

After that, run a generator that will create a coffescript file with examples of using keybindings.js.coffee and connect the library to Asset Pipeline by adding //= require mousetrap to the js application manifest.

 $ rails generate mousetrap:install 

')

Using


With the help of javascript functions already included in the created file, you can use data-attributes ( data-keybinding ) out of the box to create page navigation.

For example, a code like
 = link_to 'Homepage', root_path, data: { keybinding: 'h' } 
allows you to go to the home page by clicking on the 'h'

And this one will make the focus switch to the Username input field using the 'u' button
 = text_field_tag 'Username', nil, data: { keybinding: 'u' } 

Of course, the library features are not limited to navigation, you can call any javascript function. And you can hang up its call not only on one button, but also on the whole keyboard combo.
 //   Mousetrap.bind '4', -> alert '4 pressed!' Mousetrap.bind 'x', (-> alert 'x pressed!'), 'keyup' //  Mousetrap.bind 'command+shift+k', -> alert 'command+shift+k pressed!' false Mousetrap.bind ['command+k', 'ctrl+k'], -> alert 'command+k or ctrl+k pressed!' false //   Mousetrap.bind 'g i', -> console.log 'gi sequence pressed!' Mousetrap.bind '* a', -> console.log '* a sequence pressed!' // - Mousetrap.bind 'up up down down left right left right ba enter', -> console.log 'You WIN!' 

Learn more about the capabilities of Mousetrap on the project page.

Finally


Mousetrap copes with its responsibilities, and I'm going to develop gem further. I will be glad to any constructive feedback .

Links (where do without them)



© Photo by macrj

Source: https://habr.com/ru/post/152057/


All Articles