How to format/beautify rails erb code - ruby-on-rails

How to format/beautify rails erb code. The view code is a mix of erb and JS.
I tried using the following tool as well, but it didn't help
https://github.com/katgironpe/rails-erb-lint

A good IDE to format/beautify rails is RubyMine.
RubyMine is able to reformat many types of files, like Ruby, HTML, JavaScript, CSS, etc.
example for reformat erb file:
Before:
After:
You can set the code style in the Preferences / Editor / Code Style

The tool which you already used, i.e., rails-erb-lint, checks only for the validity of you ERB and doesn't help with beautifying the ERB code. I don't know which editor you are using, but you can try either Sublime Text 3 or Github's Atom. Both of these have 3rd party packages to beautify Ruby and ERB code. Moreover, the indentation and trailing whitespace removing ability of these editors are enough to beautify/format the ERB files, though they have menu items/ shortcuts to do this on-demand/selectively too.

If you are using Sublime Text, check out this "Sublime Text 2 & 3 Plugin to BeautifyRuby":
https://github.com/CraigWilliams/BeautifyRuby
Once installed via Sublime's Package Control System you can use the shortcut ctrl + alt + k (on Windows + Linux) or ctrl + cmd + k (on OS X) to beautify your Ruby and erb-files manually - or configure the plugin to do that automatically before saving any Ruby- and erb-file. Configuration is easy - you find the config-file here (via the Sublime- menu):
Preferences > Package Settings > BeautifyRuby > Settings - Default:
{
// Specify your ruby interpreter (below). (Note, if you are using a linux distro with Rbenv instead of RVM, then try the following path: "ruby": "~/.rbenv/shims/ruby")
"ruby": "~/.rvm/bin/rvm-auto-ruby",
// Use 2 Spaces instead of tabs:
"translate_tabs_to_spaces": true,
"tab_size": 2,
// You can change the file patterns handled by this plugin:
"file_patterns": ["\\.html\\.erb", "\\.rb", "\\.rake", "Rakefile", "Gemfile", "Vagrantfile"],
"html_erb_patterns": ["\\.html\\.erb"],
// This package offers a pre-save hook; when activated, your ruby and erb files will
// be reformatted automatically before saving (deactivated by default)
"run_on_save": false,
// The sublime command "beautify_ruby" performs a save after formatting.
// (activated by default)
"save_on_beautify": false
}
BeautifyRuby depends on the Ruby gem htmlbeautifier, which needs to be installed on your system first. Otherwise the plugin throws an error each time you try to beautify your code. Make sure, the ruby-interpreter-setting in the config file shown above points to the correct ruby which holds the htmlbeautifier-gem...

Related

Setting a default editor in Pry

I'm asking about setting a default editor for Pry to use. I'm working on a Rails
app. I created a file named ".pryrc" immediately inside my working directory.
In this file, I wrote this line of code (based on what I read on Github :
Pry.config.editor = proc { |file, line| "sublime +#{line} #{file}" }
This doesn't seem to work. when I try the command ".sublime company.rb", I 'd get
this error:
Error: there was a problem executing system command: sublime company.rb
Can someone tell me what I'm doing wrong please?
Change the configuration to:
Pry.config.editor = proc { |file, line| "sublime #{file}:#{line}" }
You start the editor in Pry by using the edit command.
For example to open test.rb at line 30 use:
edit test.rb:30
See here for more details
For those who have the same problem as mine.Perhaps, you have trouble launching the editor even outside Pry. First thing, make sure to check if the sublime command exists in ur PATH. if not, you probably need to create a symlink between the command and the corresponding path to your app within /usr/local/bin. For more information, see here.

syntaxhighlighter -- how to add the optional language pack to standard version

The standard version of syntaxhighlighter 3.0.83 ( http://alexgorbatchev.com/SyntaxHighlighter/download/ ) is similar to the plugin for Wordpress which contains an optional language pack ( http://wordpress.org/plugins/wp-syntaxhighlighter/ ) -- e.g., Biferno, Clojure, DOS batch file, F#, LISP, Lua (only for SyntaxHighlighter 3.0), MEL Script, Objective-C, PowerCLI, Processing, R, S, S-PLUS, Tcl, Verilog, Vim Script and YAML. I'm looking for a way to add the optional languages to the standard version -- any assistance in that regard would be appreciated.
Download the Wordpress plugin from:  http://wordpress.org/plugins/wp-syntaxhighlighter/  As of the date of this answer, the most recent version was wp-syntaxhighlighter.1.7.3.zip
Extract the *.js and *.css files from the subfolders within the folder lang-pack-for-wp-syntaxhighlighter and organize them to your liking. In my case, I chose to place the *.js language files inside the folder syntaxhighlighter/scripts/ in the standard version. There was only one *.css file -- i.e., shBrushProcessing.css and I chose to place that inside the folder syntaxhighlighter/styles/ in the standard version.
In your *.html file, ensure the path to the brush javascript file is correct -- e.g., for lisp use:
<script type="text/javascript" src="syntaxhighlighter/scripts/shBrushLisp.js"></script>
In your *.html file, the brush must correspond to the brush javascript file -- e.g., for lispuse:
  <pre class="brush: lisp">

auto-indent in Sublime Text 2 with Erlang after ->

How to auto-indent in Sublime Text 2 with Erlang after -> ?
I found this page: http://sublimetext.userecho.com/topic/85708-fix-increaseindentpattern-for-erlang/
How to apply it?
Do I have to use some packages such as SublimErl?
Thanks!
Update:
Install Sublime-Erlang (https://github.com/fjl/Sublime-Erlang‎) and disable the Erlang package shipped with Sublime Text 2 is the most easy way.
If the want to apply the new pattern that you linked to, than edit this file:
~/Library/Application Support/Sublime Text 2/Packages/Erlang/Indentation Rules.tmPreferences
SublimeErl looks like a cool plugin. SublimeREPL also offers Erlang support.

Aptana / Eclipse Support for "js.erb", "css.erb" files

I'm working on jRuby on Rails app in Eclipse. I recently install Aptana to better support the rails files. This provides reasonable highlighting and support for most file types includes "html.erb" files but not for other *.erb files.
It's driving me insane their must be some editor that doesn't give me a damn syntax error when I use ruby tags in js.erb files. It seems like such a basic function.
Any advice is appreciated. I am open to pretty much anything I just want some way to write javascript in erb files without a million syntax errors after every ruby tag.
This example give me a syntax error in the editor despite working perfectly fine when I run the app:
<%= render :partial => 'qunit/frame_wrapper_top' -%>
module("Carousel");
asyncTest('Slider Right Button', 1, function() {
setTimeout(function() {
var center_image = frame.find('.carouselContainer li img.current').attr('id');
var e = $q.Event("click");
$('.navButton_right').trigger( e );
setTimeout(function(){
start();
var current_center = frame.find('.carouselContainer li img.current').attr('id');
notEqual( current_center, center_image, "New item is in center");
}, 1000);
},1000);
});
I'm also looking for an editor or IDE that can handle .js.erb. Aptana (3.0.9 or 3.2.0) only seems to recognise the ERB part, the JS does not get highlighted. Maybe Emacs+nXhtml will work.
Update: nXhtml does do the job for emacs. Load the file in your ~/.emacs as described in the README, then M-x eruby-javascript-mumamo-mode !

rails.vim with ruby omnicompletion giving "Error loading rails environment" error

I'm trying to get up and working with vim with ruby on rails and am having a few problems with omni-completion.
I have downloaded the rails.vim plugin for vim, which appears to be installed, with a vim call
:Rails!
gives
rails.vim 4.3 (Rails-model-arb)
Calls to rails.vim specific functions like :Rcontroller work a dream so it all looks very promising. My problem is with omni-completion and syntax highlighting, when I ruby file for example Blog/app/models/post.rb with the following contents
1 class Post < ActiveRecord::Base
2 validates :name, :presence => true
3 validates :title, :presence => true,
4 :length => { :minimum => 5 }
5 has_[<C-X><C-O> or <C-X><C-U> or <C-X><C-P>]
6 end
I expect supertab to use the rails omni-completion to provide me with options such as "has_many" etc. I'm a little muddled up as to what each of vims completion types do (keyword local completion, omni completion, user defined completion) from the rails documentation it suggests that user defined completion should provide this functionality. When try it gives the following error:
-- User defined completion (^U^N^P) Pattern not found
Press ENTER or type command to continue
when I try the first time:
Error loading rails environment
Problem loading class "Post", was it already completed?
Press ENTER or type command to continue
when I try another time it gives me
-- Omni completion (^O^N^P) Pattern not found
However omnicompletion does work in many cases, for example if i type meth it will give me a list with method, method_defined?, method_missing, methods to choose from.
Im using pathogen to handle my vim files but my .vimrc file contains the following relavent lines.
set nocompatible
call pathogen#helptags()
call pathogen#runtime_append_all_bundles()
syntax on
filetype plugin on
filetype indent on
"set ofu=syntaxcomplete#Complete
set completeopt+=longest,menu,preview
" For code completion with a drop down menu
"au FileType python set omnifunc=pythoncomplete#Complete
let g:SuperTabDefaultCompletionType = "context"
let g:SuperTabContextDefaultCompletionType = "<c-x><c-o>"
let g:SuperTabContextTextOmniPrecedence = ['&omnifunc', '&completefunc']
let g:SuperTabCompletionContexts = ['s:ContextText', 's:ContextDiscover']
let g:SuperTabContextDiscoverDiscovery = ["&completefunc:<c-x><c-u>", "&omnifunc:<c-x><c-o>"]
" If you prefer the Omni-Completion tip window to close when a selection is
" " made, these lines close it on movement in insert mode or when leaving
" " insert mode
autocmd CursorMovedI * if pumvisible() == 0|pclose|endif
autocmd InsertLeave * if pumvisible() == 0|pclose|endif
" Set up java autocompletion
:setlocal completefunc=javacomplete#CompleteParamsInfo
au FileType java set omnifunc=javacomplete#CompleteParamsInfo
" Adding ruby completion??
" Turn on language specific omnifuncs
autocmd FileType ruby,eruby set omnifunc=rubycomplete#Complete
autocmd FileType ruby,eruby let g:rubycomplete_buffer_loading = 1
autocmd FileType ruby,eruby let g:rubycomplete_rails = 1
rails.vim is in the ~/.vim/bundle/rails directory, supertab works fine and is installed under ~/.vim/bundle/supertab
I've spent such a long time trying to figure this small thing out but have had no success! Does anyone have any ideas on where I should go from this? I believe it could be something todo with the supertab definitions in the .vimrc file, or the ruby omni-completion definitions.
If I remove the line
autocmd FileType ruby,eruby let g:rubycomplete_rails = 1
from the .vimrc file the error loading rails error disappears but of course there is no completion of the text, only a user defined completion error.
This is my first post on StackOverflow after a lot of viewing, I hope I have supplied all the relavent details!
I installed vim with MacPorts and my current version is vim #7.3.146_0+huge+perl+python27+ruby, ruby is enabled but macports wanted to install its own version, thus 1.8.7 is installed under /opt/local/ruby despite me using rvm and having 1.9.2 installed with rails 3.0.7. This could perhaps be the problem? I haven't found a way of telling macports to use a version of ruby which is already installed though.
Thanks for all your help!
I think the ruby completion is being overridden by the java line:
:setlocal completefunc=javacomplete#CompleteParamsInfo
If I comment that line out I can go into a model and do
has_<C-X><C-U>
to autocomplete has_many. (You shouldn't even need the autocmd FileType ruby,eruby ... lines.)
And yes it's smart in that n<C-X><C-U> will give you named_scope in a model but number_to_currency and friends in a view.
However rails.vim will not autocomplete custom methods, though I'm sure there are plugins out there that add that.

Resources