How to declare a ruby constant (RMagick) in a YAML file - ruby

I am looking for a possibility to declare a Magick::StyleType constant in a .yml file and then to load this constant into a ruby file.
Or if that's not possible then I need to know how to convert a String into a Magick::StyleType constant in ruby.
Here are the details:
I am trying to write a ruby program, which places some text on a picture and I use the RMagick interface for it.
In my ruby program I have a method which specifies different properties of the text like font-family or font-style. This method includes the line:
self.font_style = ItalicStyle
Now I want to store all changeable parameters in a YAML-config file (config.yml), so this config.yml includes these lines:
#font style (like bold, italic and so on)
:font_style: ItalicStyle
Now I load the config.yml in my ruby file and the above mentioned line in my method reads now
self.font_style = config_file[:font_style]
When I run my ruby file now I get the error message:
`font_style=': wrong enumeration type - expected Magick::StyleType, got String (TypeError)
So after having searched a little about the topic I changed my config.yml first to
:font_style: !/ruby/constant ItalicStyle
which got me the same error message as above and then I tried this:
:font_style: !/ruby/symbol :ItalicStyle
and got this error message:
`font_style=': wrong enumeration type - expected Magick::StyleType, got Symbol (TypeError)
Then I checked in irb:
require 'rmagick' => true
Magick.const_get(ItalicStyle) => ItalicStyle=2
Magick.const_get(ItalicStyle).class => Magick::StyleType
So, finally I get to my question: How do I need to change the line
:font_style: !/ruby/symbol :ItalicStyle
in my config.yml file so that when loaded into my ruby file ItalicStyle will be recognized as a Magick::StyleType constant?
Or when I leave
:font_style: ItalicStyle
in the config.yml and load the ItalicStyle as a String into my ruby file: is there a possibility, to convert ItalicStyle from a String to the Magick:StyleType constant in the ruby file directly?
I would be really happy if someone could help. I have tried for days to find a solution and I really need it for my project.

I would just store a String in the YAML file, because that is easier to write and to read:
:font_style: ItalicStyle
Than I would get the constant by its name to configure Magick:
self.font_style = Object.const_get(config_file[:font_style])

Related

Replacing variable value in ruby while setting the value using "set" command

I have a .properties files as below:
user:abcd
pwd:xyz
system:test
Next, I have a ruby script with Watir for browser automation. In this script, I have statements like
browser.text_field(:id => 'identifierId').set "#{user}:variable to be replaced by its value from .properties file".
Similarly, other values need to be replaced for "pwd" and "system".
I tried the solution per below posts:
Replace properties in one file from those in another in Ruby
However, "set" command is setting whatever has been paased as arguments to it instead of replacing the variable with its value.
Please help.
You have to read the information out of the file.
Most Watir users leverage yaml files for this.
config/properties.yml:
user: abcd
pwd: xyz
system: test
Then read the yaml file & parse your data:
properties = YAML.safe_load(IO.read('config/properties.yml'))
text_field = browser.text_field(id: 'identifierId')
text_field.set properties['user']
Alternately you can take a look at Cheezy's Fig Newton gem, which is designed to work with his Page Object gem

Loading Ruby scripts in SketchUp: LoadError: (eval):0:in `load': no such file to load

I have been trying to manually load Ruby scripts into SketchUp manually, using load. I always get an error back saying the file is non existent even though it is there in the directory.
Here is a sample of my code:
load "H:Document\sclf_color_by_z_1.6.1_1.rbz"
and the error messages:
Error: LoadError: (eval):0:in `load': no such file to load -- H:Document clf_color_by_z_1.6.1_1.rbz>
(eval)
(eval):0
Three issues here:
H:Document\sclf_color_by_z_1.6.1_1.rbz is not a valid path. After the Drive specifier H: you you should have a separator: \ - like so: H:\Document\sclf_color_by_z_1.6.1_1.rbz
Beware escape characters in strings when you program. \ is such a character.
To correct your string you'd have to have something like this:
"H:\\Document\\sclf_color_by_z_1.6.1_1.rbz"
https://en.wikibooks.org/wiki/Ruby_Programming/Strings#Escape_sequences
However, note that the convention for Ruby is to use forward slashes - even on Windows: "H:/Document/clf_color_by_z_1.6.1_1.rbz"
You are trying to load an RBZ file here. This is not the same as an RB file. An RBZ is a packaged SketchUp extension (actually a ZIP file). To programmatically install an RBZ you must use Sketchup.install_from_archive("H:/Document/clf_color_by_z_1.6.1_1.rbz")
http://www.sketchup.com/intl/en/developer/docs/ourdoc/sketchup#install_from_archive
Note that Sketchup.install_from_archive is nothing like load - it permanently installs the extension to SketchUp where as load would be just for that session.
Whenever you have a filepath that you think should be on disk - as the system whether it can find it: File.exist?("H:\Document\sclf_color_by_z_1.6.1_1.rbz") If that return false you know you need to carefully check your path again checking for syntax errors and typos.
You should use File.join() method. In your case:
You can't use load for a .rbz file but you can use Sketchup.install_from_archive() as thomthom said
So in your case your can simply do:
file = File.join( 'H:', 'Document' , 'sclf_color_by_z_1.6.1_1.rbz' )
Sketchup.install_from_archive file

ruby open pathname with specified encoding

I am trying to open files telling Ruby 1.9.3 to treat them as UTF-8 encoding.
require 'pathname'
Pathname.glob("/Users/Wes/Desktop/uf2/*.ics").each { |f|
puts f.read(["encoding:UTF-8"])
}
The class documentation goes through several levels of indirection, so I am not sure I am specifying the encoding properly. When I try it, however, I get this error message
ICS_scanner_strucdoc.rb:4:in read': can't convert Array into Integer (TypeError)
from ICS_scanner_strucdoc.rb:4:inread'
from ICS_scanner_strucdoc.rb:4:in block in <main>'
from ICS_scanner_strucdoc.rb:3:ineach'
from ICS_scanner_strucdoc.rb:3:in `'
This error message leads me to believe that read is trying to interpret the open_args as the optional leading argument, which would be the length of the read.
If I put the optional parameters in, as in puts f.read(100000, 0, ["encoding:UTF-8"]) I get an error message that says there are too many arguments.
What is the appropriate way to specify only the encoding? Would it be correct to say that this is an inconsistency between the documentation and the behavior of the class?
Mac OS 10.8
rvm current reports "ruby-1.9.3-p484"
I'm not sure you want to specify encoding for path name or for file itself.
If it is latter, this maybe what you want.
Pathname.glob("/Users/Wes/Desktop/uf2/*.ics").each { |f|
puts File.open(f,"r:UTF-8")
}
With Pathname.read you can write like this.
Pathname.glob("/Users/Wes/Desktop/uf2/*.ics").each do |f|
path = Pathname(f)
puts path.read
end

Ruby require_relative not loading file, not throwing error

I am having trouble getting constant definitions loaded via an external file. I have narrowed the problem down to the following.
require_relative '../../common/config.rb'
A_CONSTANT = 'something'
puts "A_CONSTANT: #{A_CONSTANT}"
When I run this as written, it prints the message correctly. The same constant is declared in the file common/config.rb. The relative path is correct for the location of this file. Just for completeness, the above code is in /watir/dashboard/spec/ex.rb. The constant is declared in /watir/common/config.rb.
As I see it, the above code should error out for a duplicate constant declaration. It does not. If I comment out the constant declaration above and rerun, the puts statement shows an error for 'uninitialized constant.' Any ideas what's wrong?
Edit - The contents of the file common/config.rb are below.
A_CONSTANT = 'something'
On a lark, I changed the filename to common/conf.rb. When I modify the require_relative statement to load the renamed file, I get the results I originally expected. The file is loaded and the second constant declaration throws a warning saying 'already initialized constant.' If I comment out the second declaration, the script runs perfectly.
It appears that the filename 'config.rb' is somehow special when loaded by a relative path. I have use that filename in other scripts where it was in the same folder as the loading script or a sub-folder. This is the first time I have had to move up the tree to load it.
Ruby allows redefining constants, and will only print a warning. Some setting in your Ruby is just hiding that warning from you.

Replace properties in one file from those in another in Ruby

I want to replace properties in one file from those in another. (I am new to ruby, and read about Ruby and YAML. I have a Java background)
Eg.
File 1
server_ip_address=$[ip]
value_threshold=$[threshold]
system_name=$[sys_name]
File 2
ip=192.168.1.1
threshold=10
sys_name=foo
The ruby script should replace the $ values by their real values (I do not know if $[] is the format used in ruby. Also do Files 1 and 2 have to be YAML files, or erb files?) and produce File 1 as :
server_ip_address=192.168.1.1
value_threshold=10
system_name=foo
I searched the web for this, but could not express it in the right keywords to find a solution/pointer to a solution/reference material on google. How can this be done by a ruby script?
Thanks
If you can switch the formats, this should be as easy as:
require 'yaml'
variables = YAML.load(File.open('file2.yaml'))
template = File.read('file1.conf')
puts template.gsub(/\$\[(\w+)\]/) { variables[$1] }
Your template can stay as-is, but the substitution file would look like:
ip: 192.168.1.1
threshold: 10
sys_name: foo
This makes it easy to read in using the YAML library.

Resources