How do you stop Intellij from reformating one line Ruby functions? - ruby

I have a ruby function like this in one of my tests:
def inject_exceptions(_) ; end
Intellij keeps reformating the function to look like this:
def inject_exceptions(_)
;
end
How do I configure it to stop doing that?

To stop IntelliJ from formatting a specific piece of code you can enable "Formatter Control" under:
Preferences -> Editor -> Code style
Tick the checkbox for Enable formatter markers in comments
And then wrap your code with:
# #formatter:off
def inject_exceptions(_) ; end
# #formatter:on
This works in any language, just make sure to put the markers in a comment.

At the moment it's not possible to configure it, but please follow the corresponding request:
https://youtrack.jetbrains.com/issue/RUBY-21387

Related

How to display debug info or console.log equivalent in Lua

I am creating many games using Lua and LOVE2D, but whenever I implement a new function and want to test it out, or simply want to know a value of a variable in Lua, I either display it on the game screen or just hope that it works.
Now my question is...
IS THERE A WAY TO DISPLAY SOME INFO, such as A VARIABLE VALUE or something else into the terminal or somewhere else? Just like console.log in javascript which displays some content in the javascript console in the browser. So, is there a way to do this is Lua?? using LOVE2D?
I am using a Mac, so I have a terminal and not a command prompt. Is there a way to display some content there? Anywhere else would also be fine, I just need to see if those values are as expected or not.
Use a conf.lua file to enable the console, then you should be able to use a standard print(). You can read the wiki entry here.
Note: You have to run Lua and Love2D via the terminal for this to work. Running Lua and Love2D like this is required for the print statements to show:
/Applications/love.app/Contents/MacOS/love "/Users/myuser/Desktop/love2d-test-proj"
You just need to add a conf.lua file to the same location where your main.lua. Your file may be as simple as this:
function love.conf(t)
t.console = true
end
But feel free to copy the whole configuration file from the above link and edit what you need.
I can't be completely sure about this, because I have no access to Mac, but the console is disabled by default and even on Windows, no prints are shown until you turn it on.
Alternatively You can also display debug info in the game itself like some games do.
What I like to do is add something like debugVariable = {} for logging events that happen in each loop and debugPermanent = {} for events that happen rarely. Possibly add convenience functions for writing to the variables:
function debugAddVariable(str)
table.insert(debugVariable, str)
end
--..and similarly for debugPermanent
Now a function to draw our debug info:
function debugDraw()
love.graphics.push() --remember graphics state
love.graphics.origin() --clear any previous transforms
love.graphics.setColor(--[[select color for debug info]])
love.graphics.setFont(--[[select font for debug info]])
for i, v in ipairs(debugPermanent) do
love.graphics.print(v)
love.graphics.translate(0, --[[fontHeight]])
end
for i, v in ipairs(debugVariable) do
love.graphics.print(v)
love.graphics.translate(0, --[[fontHeight]])
end
debugVariable = {} --clear debugVariable to prepare it for the next loop
love.graphics.pop() --recall graphics state
end
And we just call this draw function at the end of our love.draw() and the texts should appear.
Obviously, this method can be refined further and further almost infinitely, displaying specific variables, and adding graphs for some other variables to clarify the information you want to show, but that's kind of outside of the scope of the question.
Lastly Feel free to check here for debug libraries submitted by users.

How to bind a key sequence in Ruby Tk?

I am tring to bind the key sequence Control_L + Up in a Tk widget in Ruby. More explicitely, I want a proc to run when "Control_Left" and "Arrow-Up" are pressed together.
Untill now I have not been successful, I tried many combinations looking at TclTk, Python and Perl docs but I could not find the way out.
It should be something similar to
widget.bind("Control_L Up", proc {
puts "-----> sequence ok "
})
p.s. One by one the two events Control_L and Up are correcly catched.
I found it, to whoever may need it in future, this is the working snippet
require 'tk'
root = TkRoot.new()
root.minsize [400, 300]
root.geometry "+200+200"
root.bind('Control-Key-Up', proc { puts "presssed Control + Up"; } )
Tk.mainloop()
Observe that (1) it works even in form 'Control Key Up' as stated in TclTk docs. But it does not work if you write it as '<Control-Key-Up>', which is the default Tk syntax.

Is there a cucumber hook to run before and after each feature

Is there a way to run specific code block before and after each cucumber feature with certain tag?
Since setup process is very expensive I don't want to run it before each scenario.
LukasMac's answer didn't work with # variable.
Ande based on official cucumber wiki page, my example below worked and tested ok, the before hook below only execute once per feature:
Before('#my_feature_tag') do
unless $dts_test_preparation_done
# expensive setup in my case setup lots of database tables for test
$dts_test_preparation_done = true
end
end
Few days ago I've spoke with Matt Wynne (one of the core team member of cucumber gem) and he told me that there is no such feature in cucumber (at the time of writing this).
As a workaround he suggested to tag whole feature and use before each hook with a flag like so:
Before('#feature_with_expensive_setup') do
unless #setup_is_done
# perform expensive setup code here ..
#setup_is_done = true
end
end
The hooks for cucumber are described in this wiki page which show the before and after hooks you can have.
Taken from that page is this example:
The following example will cause scenarios tagged with #fast to fail if the execution takes longer than 0.5 seconds:
Around('#fast') do |scenario, block|
Timeout.timeout(0.5) do
block.call
end
end
Cucumber before and after feature hooks
Usage info
As ruby cucumber does not come supplied with the option to create hooks for before and after a feature, an ad hoc solution has been put forward.
In order to specify a hook relating to a feature, the method name must be in the following format:
before_feature_[formatted feature name]
after_feature_[formatted feature name]
Where the formatted feature name is the text from the 'Feature:' line in the feature file formatted with:
(i) all characters lowercased;
(ii) all spaces replaced with underscores; and,
(iii) all special characters deleted
Within methods matching this convention code can be specified as with scenario hooks.
Technical info
Building on the solutions by LukasMac and Gob00st I have implemented the following workarounds for my current client.
The methods go in a hooks subdirectory called AAA_special_hooks, in a special_hooks.rb file in that directory (the sole file), this is because all other things being equal the hooks will be run in the order they appear in the project structure and this way the hooks created here are run before any scenario hooks specified in other subdirectories or in the hooks base directory.
The code in the below appendix is vanilla, so far as I can see it would work for anyone.
The before hook runs on the principle of setting a global flag to ensure the hook is only run once for a feature (as per LukasMac and Gob00st). That principle has been extended to the abstract hook for two reasons, firstly to simplify the specification of hooks in general and also to have consistency with the after hook implementation.
The after hook is designed to determine whether the feature has changed since the last scenario was executed. If so the after hook will be run for the previous feature before anything happens in the current one. Clearly the vulnerability could be that the new feature has in fact been started before the after hook runs for the previous one, but I can't see how this might cause any issues. The final feature however cannot have an after hook run in this way and that is the reason for the reimplementation of that code in the at_exit method.
Appendix - special_hooks.rb code
def get_formatted_name(feature_name)
formatted_name = feature_name.downcase.gsub(' ', '_')
%w[# ' , . / ! " £ $ % ^ & * ( ) { } [ ] ; : # ~ ? < > \] + = - ` ¬ |].each { |char| formatted_name.gsub! char, '' }
formatted_name
end
Before do |scenario|
$completed_before_hooks ||= []
$feature_name ||= scenario.feature.name
unless $feature_name == scenario.feature.name
# run after hook for previous feature
begin
send "after_feature_#{get_formatted_name $feature_name}"
rescue NoMethodError
end
end
#run before hook for current feature if not already done
begin
formatted_name = get_formatted_name scenario.feature.name
unless $completed_before_hooks.include? formatted_name
$completed_before_hooks << formatted_name
send "before_feature_#{formatted_name}"
end
rescue NoMethodError
end
$feature_name = scenario.feature.name
end
at_exit do
# don't run final hook if error raised that was not handled
unless $! && $!.status > 1
puts 'EXECUTING FINAL AFTER HOOK... PLEASE WAIT'
begin
send "after_feature_#{get_formatted_name $feature_name}"
rescue NoMethodError
end
puts 'FINAL AFTER HOOK COMPLETED'
end
end
Mocking of BeforeFeature/ AfterFeature hooks is achievable by tagging the first scenario of the feature with a tag say #ExecuteBeforeFeature and last scenario with tag say #ExecuteAfterFeature and then writing the tagged Before and After hooks as following:
Before('#ExecuteBeforeFeature') do
#code in this method will be executed only before the first scenario or before the feature if only the first scenario is tagged for this hook.
end
After('#ExecuteAfterFeature') do
#code in this method will be executed only after the last scenario or after the feature if only the last scenario is tagged for this hook.
end
a modification of the first answer works for me with single quotes
Before('#feature_with_expensive_setup') do
unless '#setup_is_done'
# perform expensive setup code here ..
#setup_is_done = true
end
end
You can achieve after feature with at_exit.

What is the best way to get keyboard events (input without press 'enter') in a Ruby console application?

I've been looking for this answer in the internet for a while and have found other people asking the same thing, even here. So this post will be a presentation of my case and a response to the "solutions" that I have found.
I am such new in Ruby, but for learning purposes I decided to create a gem, here.
I am trying to implement a keyboard navigation to this program, that will allow the user use short-cuts to select what kind of request he want to see. And in the future, arrow navigations, etc.
My problem: I can't find a consistent way to get the keyboard events from the user's console with Ruby.
Solutions that I have tried:
Highline gem: Seems do not support this feature anymore. Anyway it uses the STDIN, keep reading.
STDIN.getch: I need to run it in a parallel loop, because at the same time that the user can use a short-cut, more data can be created and the program needs to show it. And well, I display formated text in the console, (Rails log). When this loop is running, my text lost the all the format.
Curses: Cool but I need to set position(x,y) to display my text every time? It will get confusing.
Here is where I am trying to do it.
You may note that I am using "stty -raw echo" (turns raw off) before show my text and "stty raw -echo" (turns raw on) after. That keeps my text formated.
But my key listener loop is not working. I mean, It works in sometimes but is not consistent. If a press a key twice it don't work anymore and sometimes it stops alone too.
Let me put one part of the code here:
def run
# Two loops run in parallel using Threads.
# stream_log loops like a normal stream in the file, but it also parser the text.
# break it into requests and store in #requests_queue.
# stream_parsed_log stream inside the #requests_queue and shows it in the screen.
#requests_queue = Queue.new
#all_requests = Array.new
# It's not working yet.
Thread.new { listen_keyboard }
Thread.new { stream_log }
stream_parsed_log
end
def listen_keyboard
# not finished
loop do
char = STDIN.getch
case char
when 'q'
puts "Exiting."
exit
when 'a'
#types_to_show = ['GET', 'POST', 'PUT', 'DELETE', 'ASSET']
requests_to_show = filter_to_show(#all_requests)
command = true
when 'p'
#types_to_show = ['POST']
requests_to_show = filter_to_show(#all_requests)
command = true
end
clear_screen if command
#requests_queue += requests_to_show if command
command = false
end
end
I need a light in my path, what should I do?
That one was my mistake.
It's just a logic error in another part of code that was running in another thread so the ruby don't shows the error by default. I used ruby -d and realized what was wrong. This mistake was messing my keyboard input.
So now it's fixed and I am using STDIN.getch with no problem.
I just turn the raw mode off before show any string. And everything is ok.
You can check here, or in the gem itself.
That's it.

Is there a way to fold all multi-line Ruby comments in Vim?

I'm working on a Ruby gem and I would love to be able to hide all the documentation comments in the file because they are more for people using the library than reading or writing the code. I see the value in having the comments, but when I'm working on the code they are visually distracting to me.
In MacVim I can manually fold lines of code by selecting them and clicking Tools > Folding > Create Fold, but is there a way to automatically hide all comments using some sort of shortcut?
For example, the following code:
# Returns a 2D array for Rails select helper options.
# Also used internally for Formtastic support
#
# ==== Example
# # Create an Enum with some elements
# class Priority < ClassyEnum::Base
# end
#
# class Priority::Low < Priority; end
# class Priority::ReallyHigh < Priority; end
#
# Priority.select_options # => [["Low", "low"], ["Really High", "really_high"]]
def select_options
map {|e| [e.text, e.to_s] }
end
would be displayed as:
def select_options
map {|e| [e.text, e.to_s] }
end
You could try this method:
:set fdm=expr
:set fde=getline(v:lnum)=~'^\\s#'?1:getline(prevnonblank(v:lnum))=~'^\\s#'?1:getline(nextnonblank(v:lnum))=~'^\\s*#'?1:0
The problem is that this method would become the only folding option so that's probably a little bit extreme.
I guess you would like to play with vim’s foldmethod setting. Sorry for slightly vague answer, but I have no MacVim here so you are supposed to adjust directories/filenames in my suggestion yourself.
First of all, try :setlocal foldmethod=syntax in command mode to enable folding within your current file only. If it works, you have all the prerequisites installed (namely, the ruby.vim syntax file.) Try to add let ruby_fold=1 to your .vimrc file. The latter should enable folding over all ruby files (or, alternatively you may explicetely set folding to true for all filetypes supporting folding with set foldmethod=syntax.)
Now you are to find ruby.vim over your file system to tune it up. To give a hint, on Linux distros it’s located at /usr/share/vim/vim73/syntax/ruby.vim. My syntax file enables folding for all the stuff which “may” be folded (e. g. functions, methods, etc.) Copy the original file to your $HOME/.vim/syntax directory and adjust it according to your needs. Navigate through it (by searching for fold, for instance) and remove fold keyword where you don’t want the folding is applied. The names in syntax file are self-explanatory, so you would not be in trouble here.
Restart vim and enjoy your folding. Hope that helps.

Resources