What does <tt> stand for in Ruby comments? - ruby-on-rails

Going over source code written in Ruby, like Rails, I often see that small code is wrapped with tt tag, like in rails/activesupport/core_ext/array/access.rb
# Equal to <tt>self[2]</tt>.
#
# %w( a b c d e).third # => "c"
def third
self[2]
end
What is the convention behind this, when and why it was decided to use this notation?

Yep, my mistake, sorry
This is a part of special RDoc system.
Non-verbatim text can be marked up:
italic: word or <em>text</em>
bold: word or <b>text</b>
typewriter: word or <tt>text</tt>
Read more about it here

Found it by myself in the Rails documentation guide.
Using a pair of +...+ for fixed-width font only works with words; that
is: anything matching \A\w+\z. For anything else use <tt>...</tt>,
notably symbols, setters, inline snippets, etc:

Related

How to control text indentation when writing to file from custom generator

Writing my first generator. Struggling to figure out how to control the indentation.
I found a few methods here and here but it wasn't really clear to me how or if I can apply these.
The generator itself works as expected, it is just annoying that the indentation is wonky and I have to either ignore it or go into the file and fix it (which defeats the purpose of automating the generation of the file content).
Not really sure what relevant code would help, this is how I generate the additional code (one basic example).
def add_site_wide
inject_into_file './app/controllers/application_controller.rb',
after: "class ApplicationController < ActionController::Base\n" do <<-'RUBY'
default_form_builder MdbFormBuilder
RUBY
end
end
Probably pretty easy to see what is going on, the only issue is the line being written default_form_builder MdbFormBuilder indented quite a bit, I can move it around and it does get placed correctly, but then the file generating it looks wonky and becomes hard to read with more content.
Is there a way to apply a method to this, or something else, that would allow me to also pass how many spaces to indent the text?
It really seems like something that should be doable, but I cannot find anything on how to achieve this.
Using the <<- will preserve whitespace on the string.
You could use << but it would required you to put the end of string mark without any indentation aswell.
To keep things pretty, the String class has a method for what you need and it is String#strip_heredoc. This will the indentation on every line.
<<-EOS
i
have
indentation
EOS
will result into
"
i
have
indentation
"
using
<<-EOS.strip_heredoc
i
have
no
indentation
EOS
will result into
"
i
have
no
indentation
"
You could use #engineersmnky sugestion with it to add indentation as needed
<<-EOS.strip_heredoc.indent(2)
i
have
two
indentations
EOS
will result into
"
i
have
two
indentations
"

How to display plain text from markdown [duplicate]

I'm currently using BlueCloth to process Markdown in Ruby and show it as HTML, but in one location I need it as plain text (without some of the Markdown). Is there a way to achieve that?
Is there a markdown-to-plain-text method? Is there an html-to-plain-text method that I could feel the result of BlueCloth?
RedCarpet gem has a Redcarpet::Render::StripDown renderer which "turns Markdown into plaintext".
Copy and modify it to suit your needs.
Or use it like this:
Redcarpet::Markdown.new(Redcarpet::Render::StripDown).render(markdown)
Converting HTML to plain text with Ruby is not a problem, but of course you'll lose all markup. If you only want to get rid of some of the Markdown syntax, it probably won't yield the result you're looking for.
The bottom line is that unrendered Markdown is intended to be used as plain text, therefore converting it to plain text doesn't really make sense. All Ruby implementations that I have seen follow the same interface, which does not offer a way to strip syntax (only including to_html, and text, which returns the original Markdown text).
It's not ruby, but one of the formats Pandoc now writes is 'plain'. Here's some arbitrary markdown:
# My Great Work
## First Section
Here we discuss my difficulties with [Markdown](http://wikipedia.org/Markdown)
## Second Section
We begin with a quote:
> We hold these truths to be self-evident ...
then some code:
#! /usr/bin/bash
That's *all*.
(Not sure how to turn off the syntax highlighting!) Here's the associated 'plain':
My Great Work
=============
First Section
-------------
Here we discuss my difficulties with Markdown
Second Section
--------------
We begin with a quote:
We hold these truths to be self-evident ...
then some code:
#! /usr/bin/bash
That's all.
You can get an idea what it does with the different elements it parses out of documents from the definition of plainify in pandoc/blob/master/src/Text/Pandoc/Writers/Markdown.hs in the Github repository; there is also a tutorial that shows how easy it is to modify the behavior.

Rails: Is it a bad idea to put double-byte character inside a model?

I've learnt that you may define a Ruby source file as UTF-8 to be able to key inside it double-byte characters (e.g.: ¤) instead of their HTML code (e.g.: & curren;):
# encoding: UTF-8
class Price < ActiveRecord:Base
def currency_symbol
'¤'
end
end
Without the encoding statement, I would need to write '& curren;'.html_safe as the core of the method.
I don't like the later because it assume I'm writing HTML (I have Excel output in my app on top of HTML).
My question is: Is there any problems or performance hits I must be aware while doing this?
Note: Ruby 2.0 brings UTF-8 as the default encoding; does it mean all Ruby files will automatically support all those characters?
Character chart: http://dev.w3.org/html5/html-author/charref
This is exactly the kind of thing that should go in the locales (config/locales). These are YAML files that define words and characters that will be used in the various parts of your application, including currency symbols. It also has the benefit of allowing you to easily introduce translations for other languages.
Take a look at the ruby on rails guide for i18n for more.

Guidance for how to add nicely formatted output to a custom rails generator

Like the title says - I want to add my custom output to a rails generator - much like you see identical - xxx or force - xxx
I want to add special, nicely formatted warnings for my custom generator - only I don't see any guidance for doing that, other than using puts
For example, I'd like to see:
Warining: Missing Related Data File
Where the word warning would be written in red. Very similar to what you see in a typical rails generator command...
Rails' generators are based on Thor. When you raise a Thor::Error the output will automatically be colored red. For example:
raise Error, "Warning: Missing related data file"
This will color the whole message red (and suppress the backtrace for cleaner output).
Furthermore you can use any of Thor's actions in your generator and several, e.g. say and yes?, support a second color argument, allowing you to do e.g.:
say_status "OK", "Blue is my favorite color", :blue
The available colors are shown here.
Finally, you can call set_color directly for fine-grained control of formatting, e.g.:
say set_color( "STOP ", :red ) +
set_color( "CAUTION ", :yellow ) +
set_color( "GO!", :green, true )
(If the third parameter is true the output will be bold.)
I hope that's helpful—but please use it responsibly!

Replace umlaute (äüö) for SEO link in rails - best way

I'm using the permalink_fu plugin to create permalinks from titles. My problem is: If the title contains german characters, they are just replaced with '_'.
What I need is something that replaces
ä with ae
ü with ue
ö with oe
I fount String.tr but the problem here is that it replaces 1 character with 1 replacement, so it would work for replacing
é with e
ø with o
etc.
Does anyone have a nice and clean solution for that?
Thanks
Look at transliterate and parameterize (with transliterations in locales/de.yml):
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate
I18n.transliterate("Über der Höhenstraße")
=> "Ueber der Hoehenstrasse"
http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize
"Über der Höhenstraße".parameterize
=> "ueber-der-hoehenstrasse"
If you don't want to write the transliterations yourself, you can install the rails-i18n gem.
I have written a small Library called Asciify for exactly that purpose
$ sudo gem install asciify
Usage:
#!/bin/ruby
require "asciify"
"Lücke".asciify #=> "Luecke"
You can provide a YAML-file for custom mappings like so:
translator = Asciify.new("/path/to/mappings.yaml")
output_string = translator.convert("input string")
(see the builtin default mapping for the expected format)
The whole project is quite old, but maybe it does the job you need it to. If not, maybe the source code will be helpful.
Use String.gsub():
"ich bin doch nicht blöd, mann!".gsub(/[äöü]/) do |match|
case match
when "ä"
'ae'
when "ö"
'oe'
when "ü"
'ue'
end
end
Of course, the lookup can be improved by using a lookup table, but the principle should be clear.
"äöü".gsub('ä','ae').gsub('ö','oe').gsub('ü','ue')
;)
Try String.sub!.
I asked a similar question once. It was for JavaScript, and it takes a regex based aproach. Maybe the solution still carries some value for you, methodologically speaking.
Try using this: "Ich bin doch nicht böld ähhh ühh öhhh".gsub(/[äöüßÄÖÜ„“§%&–+]/){|t|t.to_xs}

Resources