Archive of posts with category 'Ruby'

Ruby Openssl Version

There is a problem if I use a version of ruby with a newer version of openssl than what is on the server. Here’s the command to find out what version of openssl that ruby is using.

Learning DragonRuby

I was on vacation this week. So I had some time to do anything I wanted. For a while now, I’ve wanted to try to create a simple game. I’ve also wanted to learn how to use DragonRuby, which I purchased last year. Then, I found these videos. The guy made a basic tetris clone in a couple of hours. I figured I’d give it a try and see what I could do. Needless to say, it took me a bit over two hours…more like five or six over a couple of days. But I eventually got the game to run. My game has more bugs than the game in the tutorial. Mainly because I didn’t exactly know what I was doing and because I was trying to copy the code from the video, which was hard to read. I tried downloading his final code to compare it to mine, but I couldn’t find it. If I wanted to spend more time to figure out my mistake, I probably could. But the main thing I wanted to learn was how to go about making a game and how to use the DragonRuby workflow. Even with my buggy final game, I definitely learned more about those two things. So I feel like this was time that was well spent.

Using a Barcode Scanner

I got a Tera 1D Barcode scanner at work. What I want to use it for is to be able to scan a barcode on a circuit board and then print out more labels with barcodes to stick on the boxes that we’ll be shipping them in. I also have an old iMac that I’m going to use for this project, along with a Brother QL 550 label printer.

MacPorts, gems and ruby notes

I’ve had a number of issues with my macports, ruby and rails setup after I updated the OS to 12.1. First I want to document some things that helped me to figure out some of my problems.

Downgrading MacPorts Packages

I use macports (not homebrew) as my package manager on my mac for some software that I need to use with Ruby on Rails. From time to time, I’ll get an error like this when I try to start a rails server.

It's Up!

I finally finished editing all of my old posts that had absolute paths to images in the urls. And I edited all the paths in my image galleries, which thankfully had relative paths. So it was pretty easy to fix.

My First Sinatra Project

I have a wufoo form that I’m using and I want to automatically see the results on a webpage. One of the hangups of this process is that I can’t put any script on the webserver. But what I can do is embed an iframe. So I could download the information that I wanted from my form to another server and then display that page in the iframe. My question was what to run on my second server, which I’m going to call my results server. All it really needed to do was get the results and then show them. So using a ruby on rails app for this seemed to be overkill. After reading about it, sinatra seemed to be the perfect fit. I could still use ruby and just show the results I wanted. This seemed to be the perfect project to test out sinatra.

Using Ruby on XML Files

I need to copy some data from one system to another. On the first system, I can download an xml file. The second system is a ruby on rails website. So I’d like to them upload the xml file to the site and have it enter in the data. But since I’m not that familiar with working with xml files, I thought I’d work on it from the command line first.

In ruby, there’s a gem called nokogiri which works with xml (or html) files. Here’s the sample xml file that I’m using:


<AbstractBook>
 <Conference>TEST CONFERENCE 2016</Conference>
 <abstract>
  <Id>5</Id>
  


  Diversity, diversity

  <Content>This is all about diversity.</Content>
  <field id="content">This is all about diversity.</field>
  <PrimaryAuthor>
   <FirstName>George</FirstName>
   <FamilyName>Washington</FamilyName>
   <Email>george@wh.gov</Email>
   <Affiliation>WH</Affiliation>
  </PrimaryAuthor>
  <Speaker>
   <FirstName>George</FirstName>
   <FamilyName>Washington</FamilyName>
   <Email>george@wh.gov</Email>
   <Affiliation>WH</Affiliation>
  </Speaker>
  <ContributionType>Abstract</ContributionType>
  <Track>Diversity and Inclusion </Track>
  <AcceptedTrack>Diversity and Inclusion </AcceptedTrack>
 </abstract>
 <abstract>
  <Id>6</Id>
  


  Higgs, higgs, higgs

  <Content>I've got *something to say* out the **Higgs.**</Content>
  <field id="content">I've got *something to say* out the **Higgs.**</field>
  <PrimaryAuthor>
   <FirstName>Abe</FirstName>
   <FamilyName>Lincoln</FamilyName>
   <Email>abe@wh.gov</Email>
   <Affiliation>The White House</Affiliation>
  </PrimaryAuthor>
  <Speaker>
   <FirstName>Abe</FirstName>
   <FamilyName>Lincoln</FamilyName>
   <Email>abe@wh.gov</Email>
   <Affiliation>The White House</Affiliation>
  </Speaker>
  <ContributionType>None</ContributionType>
  <Track>Higgs Physics</Track>
  <AcceptedTrack>Higgs Physics</AcceptedTrack>
 </abstract>
 <abstract>
  <Id>7</Id>
  


  Oh the Lovely Higgs

  <Content>Some interesting info about how pretty the Higgs is.</Content>
  <field id="content">Some interesting info about how pretty the Higgs is.</field>
  <PrimaryAuthor>
   <FirstName>Grover</FirstName>
   <FamilyName>Cleveland</FamilyName>
   <Email>gc@wh.gov</Email>
   <Affiliation>WH</Affiliation>
  </PrimaryAuthor>
  <Speaker>
   <FirstName>Grover</FirstName>
   <FamilyName>Cleveland</FamilyName>
   <Email>gc@wh.gov</Email>
   <Affiliation>WH</Affiliation>
  </Speaker>
  <ContributionType>None</ContributionType>
  <Track>Higgs Physics</Track>
 </abstract>
</AbstractBook>

And here’s the script I wrote:

#!/Users/maryh/Software/rubies/2.2.3/bin/ruby

require 'nokogiri'

File.open("Abstracts.xml") do |file|
	@doc2 = Nokogiri::XML(file)
	elems = @doc2.xpath("//Speaker")
	myfirst ='Abe'
	mylast = 'Lincoln'
	elems.each do |e|
		if (e.at('FirstName').text == myfirst) && (e.at('FamilyName').text == mylast)
			puts e.parent.at('Title').text
			puts e.parent.at('Content').text
			print "#{e.at('FirstName').text} " 
			print "#{e.at('FamilyName').text}\n"
		end
	end

end

First, I open the file and open it as an xml file with nokogiri. I then put in elems all the xml fields labelled “Speaker”. I then cycle through elems looking for the string “Abe” and “Lincoln”. If I find them both, I print out the field “Title” and “Content” which are both in the parent field from “Speaker” and then I print out the first and family names.

This is very basic and there are a lot more things that I need to do. I need to match the speaker info with names stored in a model in my rails app. And then update that entry with the title and content if I find a match.

Using Ruby on CSV Files

I’m working with some different systems for a conference I’m working on. We’re using RegOnline to handle the registrations. One of the things that I need to do is get a list of people who have registered on RegOnline and post them on our conference website. Our conference site is plain html and I don’t want to have to type in each person who registers. I can download a csv file from RegOnline. I want to write a script that reads the downloaded csv file and makes an html file for the website. I hadn’t done much with csv files before, but here’s a basic script that pretty much does what I want. (I still have to put html tags in, but that should be pretty easy.)

Ruby Lambdas

I’ve used ruby lambdas a few times, but I have to admit that I never really understood them. However, I’ve now come across a case where I have to figure them out. Here’s what I’ve found:

Changing Password Encryption

Per my earlier post about changing the encryption methods of passwords, I had a chance to test out the directions I had to see if they really worked. In fact, they worked perfectly. And to check that things actually changed, I took a look at the crypted password before and after I logged in.

Handy Trick

If you have some sample code in a ruby file that you want to run ONLY when that file is called directly, enclose it in the following if statement.

Ruby Methods

I’m still learning where methods go when writing ruby on rails applications. I read something earlier today (and had read it before) that you need to think “tell, don’t ask” when it comes to methods. So basically when working with an object, if you want it to do something, you tell it to do that. This method will then go into the model and get called with @object.method. So, in my application, after an applicant is saved. I want to send a message to the object to send email to that applicant. I had this in the controller, but now I’m pretty sure that this belongs in the model. It ends up looking like this:

Ruby Dates

In one of my apps, the price of registration for an event goes up after a particular date. So I have to check if today’s date is after the given date. Here’s how I’ll do this:

Libv8 Gem Problems

I had some problems installing the libv8 gem after installing ruby 2.0. The solution was to use yum to install the python26 packages and then make a link from them to /usr/local/bin/python. After that the gem install libv8 command worked.

Ruby 2.0 with Other Versions

Ruby 2.0.0 came out today and I thought I’d install it. I had been using rvm to handle my multiple versions of ruby, but when I tried to do a rvm install 2.0.0, I got a bunch of errors about homebrew. It seems as though homebrew is now required. This is a problem for me because I’ve been using MacPorts for years and I just don’t feel like switching right now. So, I figured that I’d just see if I could compile it myself by hand and come up with a way to have multiple versions of ruby. The thing is, I really don’t switch between versions all that much. I will now, as I slowly convert all the sites I have to 2.0. So I’ll need to go back and forth a little. But once it’s done, I probably won’t switch for a long time. I’ve been on 1.9.3 for a very long time and it worked fine. Anyway, I’m not exactly sure how I’ll do this, but I’m going to give it a try.

First step, was to update XCode and then go into Preferences and update the command-line tools. In the ruby download, my config command was pretty basic:

ant:ruby-2.0.0-p0 $ ./configure --prefix=/Users/maryh/Software/rubies/2.0.0-p0

Putting everything in a Software/rubies/version directory seems to be a good idea. I could be completely wrong about this, but that’s how I’m starting. My first make attempt failed with an error like this:

compiling ./missing/setproctitle.c
compiling dmyext.c
linking miniruby
/Users/maryh/Downloads/ruby-2.0.0-p0/lib/fileutils.rb:111: [BUG] Stack consistency error (sp: 38, bp: 36)
ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-darwin12.2.0]

-- Crash Report log information --------------------------------------------
...

I needed to set CC=clang (it was CC=gcc-4.2) and that fixed this problem.

New error:

compiling readline.c
readline.c:1688:9: error: use of undeclared identifier 'username_completion_function'; did you mean
      'rl_username_completion_function'?
                                    rl_username_completion_function);
                                    ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                                    rl_username_completion_function
readline.c:75:42: note: expanded from macro 'rl_username_completion_function'
# define rl_username_completion_function username_completion_function
                                         ^
/usr/local/include/readline/readline.h:449:14: note: 'rl_username_completion_function' declared here
extern char *rl_username_completion_function PARAMS((const char *, int));
             ^
1 error generated.

Readline errors are apparently common. Again, I’m pretty sure this is related to the fact that I’m using MacPorts. My fix was to:

ant:ruby-2.0.0-p0 $ export LDFLAGS="-L/opt/local/lib"

Then rerun configure and make and things worked. Everything is installed in /Users/maryh/Software/rubies/2.0.0-p0. And the gem environment is:

ant:bin $ ./gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 2.0.0
  - RUBY VERSION: 2.0.0 (2013-02-24 patchlevel 0) [x86_64-darwin12.2.0]
  - INSTALLATION DIRECTORY: /Users/maryh/Software/rubies/2.0.0-p0/lib/ruby/gems/2.0.0
  - RUBY EXECUTABLE: /Users/maryh/Software/rubies/2.0.0-p0/bin/ruby
  - EXECUTABLE DIRECTORY: /Users/maryh/Software/rubies/2.0.0-p0/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86_64-darwin-12
  - GEM PATHS:
     - /Users/maryh/Software/rubies/2.0.0-p0/lib/ruby/gems/2.0.0
     - /Users/maryh/.gem/ruby/2.0.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - http://rubygems.org/

So, now I think I can just install gems there and see how things go.

Ruby File Open Options

I spent a little time looking for this info, so I thought I’d post it here. Use it like this:

File.open("#{output}","a") do |w|
  w << "#{Time.now.to_s(:datetime_stamp)} Other text to write
end

Remember if you use File.open or CSV.open with a block, the file is automatically closed when the block closes. Otherwise you have to close the file.

  Mode |  Meaning
  -----+--------------------------------------------------------
  "r"  |  Read-only, starts at beginning of file  (default mode).
  -----+--------------------------------------------------------
  "r+" |  Read-write, starts at beginning of file.
  -----+--------------------------------------------------------
  "w"  |  Write-only, truncates existing file
       |  to zero length or creates a new file for writing.
  -----+--------------------------------------------------------
  "w+" |  Read-write, truncates existing file to zero length
       |  or creates a new file for reading and writing.
  -----+--------------------------------------------------------
  "a"  |  Write-only, starts at end of file if file exists,
       |  otherwise creates a new file for writing.
  -----+--------------------------------------------------------
  "a+" |  Read-write, starts at end of file if file exists,
       |  otherwise creates a new file for reading and
       |  writing.
  -----+--------------------------------------------------------
   "b" |  Binary file mode (may appear with
       |  any of the key letters listed above).
       |  Suppresses EOL <-> CRLF conversion on Windows. And
       |  sets external encoding to ASCII-8BIT unless explicitly
       |  specified.
  -----+--------------------------------------------------------
   "t" |  Text file mode (may appear with
       |  any of the key letters listed above except "b").
Regex in Ruby

This is something simple that I should know off the top of my head, but seemed to have forgotten today. So I’m writing it here, to hopefully, help me to remember.

On one of the webapps I’ve written, someone signed up but had an apostrophe in their name. I had already accounted for spaces in names, but not apostrophes. So, I decided that I should fix things for any non-word character.

The method that cleans up the name is this:

def fullname_no_spaces
  [firstname.gsub(" ","_"), lastname.gsub(" ","_")].join("_")
end

This just substitutes any spaces it finds with an underscore. To have it replace any non-word character with an underscore, I just changed it to this:

def fullname_no_spaces
  [firstname.gsub(/\W/,"_"), lastname.gsub(/\W/,"_")].join("_")
end

That fixed my problems. For further reference, here are the regex values I could use:

^  beginning of a line or string 
$  end of a line or string 
.  any character except newline 
\w  word character[0-9A-Za-z_] 
\W  non-word character 
\s  whitespace character[ \t\n\r\f] 
\S  non-whitespace character 
\d  digit, same as[0-9] 
\D  non-digit 
\A  beginning of a string 
\Z  end of a string, or before newline at the end 
\z  end of a string 
\b  word boundary(outside[]only) 
\B  non-word boundary 
\b  backspace(0x08)(inside[]only) 
[ ] any single character of set 
*   0 or more previous regular expression 
*?  0 or more previous regular expression(non greedy) 
+  1 or more previous regular expression 
+?  1 or more previous regular expression(non greedy) 
{m,n}   at least m but most n previous regular expression 
{m,n}?  at least m but most n previous regular expression(non greedy) 
?  0 or 1 previous regular expression 
|  alternation 
( )  grouping regular expressions 
(?# )  comment 
(?: )  grouping without backreferences 
(?= )  zero-width positive look-ahead assertion 
(?! )  zero-width negative look-ahead assertion 
(?ix-ix)  turns on (or off) `i' and `x' options within regular expression.

I use a few of these a lot, but I need to remember all of them because they’re really handy. Perhaps, I’ll make a printout and hang it in my office.

Ruby Enumerators

I have a rails app that handles a lot of information about a set of experimental plates. Along with holding information about each plate, I have another table locations, that’s nested with the plates, as in plates has_many locations and locations belongs_to plates. The locations is a separate table because these plates can get shipped to different locations a lot. This is a way for us to track where all the plates are. Most importantly, we want to know which location for a give plate has the latest date, because this will tell us where the plate currently is.

RubyGems Notes (from Google Cache)

Originally posted October 15, 2009

I’ve been trying to do some stuff with ruby on rails and getting my program up and running here on coldandheartless. I had all kinds of trouble when I finally got to the deployment stage. The first errors I got were:

yo:site maryh$ cap deploy:setup
/Library/Ruby/Site/1.8/rubygems.rb:280:in `activate’: can’t activate net-sftp (= 1.1.0, runtime)
for [], already activated net-sftp-2.0.2 for ["capistrano-2.0.0"] (Gem::LoadError)
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:35:in `require’
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/
gems/capistrano-2.0.0/lib/capistrano/upload.rb:2
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require’
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require’
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/
capistrano-2.0.0/lib/capistrano/configuration/actions/file_transfer.rb:1
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `gem_original_require’
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require’
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/
capistrano-2.0.0/lib/capistrano/configuration.rb:12
… 7 levels…
from /Library/Ruby/Site/1.8/rubygems/custom_require.rb:31:in `require’
from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/
capistrano-2.0.0/bin/cap:3
from /usr/bin/cap:19:in `load’
from /usr/bin/cap:19

After screwing around for a very long time, I found that I seem to have some old versions of gems that were messing me up. And I when I tried to uninstall them, I got this error:

yo:gems root# gem uninstall capistrano -i /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8
Remove executables:
cap, capify

in addition to the gem? [Yn] Y
ERROR: While executing gem … (Gem::FilePermissionError)
You don’t have write permissions into the /System/Library/Frameworks/Ruby.framework/
Versions/1.8/usr/lib/ruby/gems/1.8/bin directory.

So I went to go and look at the above directory and it’s true that I don’t have write permissions because there was no bin directory there at all. After I created the bin directory, I was able to uninstall the gems. So now I should be able to uninstall the old stuff and put the newest files on.