Ruby convert single quotes to double quotes in XML - ruby-on-rails

Despite the fact that XML attributs can be defined using single or double quotes, my user is trying to integrate my software with another one that will not accept single quoted attribut values.
I user REXML to generate my XMLs.
Is there a way to REXML generate double quoted attribute values?
If not, is there a way for me to convert it easily?
Thanks

As of Feb 2007 there's a supported way of determining the quoting character. The changes were merged into Ruby sources on Jul 2007 and should be available on all versions since 1.8.6-p110:
require 'rexml/document'
doc = REXML::Document.new
doc.context[:attribute_quote] = :quote # <-- Set double-quote as the attribute value delimiter
root = doc.add_element('root')
root.add_attribute('val', '123')
doc.write(STDOUT)
Running that yields:
$ ruby test.rb
<root val="123"/>
$

I've seen this code around to do this. But it's from a 2003 mailing list post that also promises a more elegant (and supported) way of doing it. Might not be the best, but it could work, give it a try.
REXML::Attribute.class_eval( %q^
def to_string
%Q[##expanded_name="#{to_s().gsub(/"/, '"')}"]
end
^ )

Related

Double quoted strings in schema.rb

It may be a bit trivial question, but always bothered me:
Are there any specific reasons for Rails to use double quoted strings instead of single quoted strings (as rubocop suggests) in schema.rb?
You may find it useful to exclude the schema file from Rubocop's inspections by adding it to the .rubocop.yml file:
AllCops:
Exclude:
- db/schema.rb
The reason schema.rb is using double quotes is that most of the formatting is done by calling #inspect on a number of predefined strings, e.g.:
# schema_dumper.rb:91
stream.puts " enable_extension #{extension.inspect}"
And String#inspect prints the string with surrounding double quotes, i.e.:
"foo".inspect
#=> "\"foo\""
That said, RuboCop is there to catch human mistakes, so there's no need to include files generated by the framework, which are not meant to be edited manually. (You would still want to inspect application files created using the Rails generators.)

Foreign character issue with CSV import to Heroku Postgres DB

I have a rails app where my users can manually set up products via a web form. This works fine and accepts foreign characters well, words like 'Svölk' for example.
I now have a need to bulk import products and am using FasterCSV to do so. Generally this works without issue, but when the CSV contains foreign characters it stalls at that point.
Am I correct to believe the file needs to be UTF-8 in the first instance?
Also, I'm running Ruby 1.8.7 so is ICONV my only solution for converting the file? This could be an issue as the format of the original file won't be known.
Have others encountered this issue and if so, how did you overcome it?
You have two alternatives:
Use ensure_encoding gem to find the actual encoding of the strings.
Use Ruby to determine the file encoding using:
File.open(source_file).read.encoding
I prefer the first approach as it tries to detected the encoding based on Strings, and tries to convert to your desired encoding (UTF-8) and then you can set the encoding on FasterCSV options.

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.

understand line of code using rails bundler gem class methods: spec = Bundler.load_gemspec(Dir["./{,*}.gemspec"].first)

I'm trying to load a ruby on rails app called fatfreecrm (https://github.com/fatfreecrm/fat_free_crm).
Cannot run off rails development server on my machine. Code fails due to the following line:
spec = Bundler.load_gemspec(Dir["./{,*}.gemspec"].first)
(line 32 in project Gemfile: https://github.com/fatfreecrm/fat_free_crm/blob/master/Gemfile).
Trying to diagnose the problem but having trouble understanding what this does. In particular what directory does ["./{, *}.gemspec" refer to? Dont understand the {, *} shorthand.
Thanks
Evan
That's standard Unix shell glob syntax for a list of options that get expanded. I.e. in a Unix shell
foo{a, b, c}bar
will get expanded to
fooabar foobbar foocbar
So,
./{, *}.gemspec
will get expanded to
./.gemspec ./*.gemspec
In Ruby's Dir::[] those don't get expanded like in the shell, but they are treated as a pattern against which to match the filenames, similar to how a regex works.
See the documentation for Dir::[], which refers to the documentation for Dir::glob, for details.

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