Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Monday, March 21, 2011

hornets eye install

http://www.wedesoft.demon.co.uk/hornetseye-api/file.Installation.html
sudo aptitude install build-essential ruby1.8 ruby1.8-dev irb1.8 rubygems1.8 rake libswscale-dev

first problem


googled "sh: rake1.8: not found" and got a solution. it even has a little explanation of what's wrong and suggested short, medium, and long term workarounds.
sudo su -
rake=/usr/bin/rake gem install malloc

another workaround

i initially didn't encounter this problem because i had started off using rvm and creating a gemset for hornetseye. then i thought i should follow the instructions on the site more closely to avoid headaches. so that's funny. rvm sets up the paths and stuff correctly i guess, so the rvm install of 1.8.7 has no problem finding the rvm install of rake.

second problem

same as the first one, but with multiarray in place of malloc. again, not a problem when i was using rvm.

screw it, using rvm

i'll keep using rvm until i run across some problem forcing me to do it without rvm.

hornetseye-frame problem

installing hornets-frame complains too:

looks like it needs some boost lib. off to google again. also i tried installing the yard gem, but that gave some error output, so i abandoned it... but turns out the solution presents itself in the next step anyways. gem install yard
googled for "fatal error: boost/smart_ptr.hpp: No such file or directory" and got this (among others). need to sudo aptitude install -y libboost-dev

yet another hornetseye-frame problem

this time, hornetseye-frame installed, but its documentation seems to have failed.

but it looks like the solution is right there in the error output, so i'll try installing bluecloth like it says: gem install bluecloth. after this, i retried installing yard, in case there was stuff it failed to do on the failed install attempt in the last step. gem install yard

tangent on yard gem

so yard sure did have a ton of other stuff to do.
gem install yard gave a ton of output like this:
[error]: Exception occurred while generating 'YARD/Server/Commands/ListMethodsCo
mmand.html'  
[error]: ArgumentError: wrong number of arguments (1 for 0)
[error]: Stack trace:
        /home/ozzloy/.rvm/rubies/ruby-1.8.7-p330/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:35:in `raise'
        /home/ozzloy/.rvm/rubies/ruby-1.8.7-p330/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:35:in `require'
        /home/ozzloy/.rvm/gems/ruby-1.8.7-p330@hornetseye/gems/yard-0.6.5/lib/yard/templates/helpers/html_helper.rb:456:in `simple_markup_html'
        /home/ozzloy/.rvm/gems/ruby-1.8.7-p330@hornetseye/gems/yard-0.6.5/lib/yard/templates/helpers/html_helper.rb:81:in `html_markup_rdoc'
        /home/ozzloy/.rvm/gems/ruby-1.8.7-p330@hornetseye/gems/yard-0.6.5/lib/yard/templates/helpers/html_helper.rb:42:in `send'
        /home/ozzloy/.rvm/gems/ruby-1.8.7-p330@hornetseye/gems/yard-0.6.5/lib/yard/templates/helpers/html_helper.rb:42:in `htmlify'
to google again, searching for
[error]: Exception occurred while generating 'YARD/Server/Commands/ListMethodsCo
mmand.html'
which yielded nothing. this time i searched for "ubuntu yard gem" and got jenny fong's blog entry dealing with yard on ubuntu. from there i gathered i needed to start fresh with rdoc and yard, which i did like this:
sudo gem uninstall rdoc # complained that rdoc wasn't installed
gem uninstall rdoc # also complained that rdoc wasn't installed
gem install rdoc # took a while, but worked
gem install yard

thankfully, that worked.

yard gem tangent done

retrying the hornetseye-frame install: gem install hornetseye-frame
it worked! on to the next line.

hornetseye-{alsa,1394}

this worked just fine:
sudo aptitude install -y libasound2-dev
gem install hornetseye-alsa
sudo aptitude install -y libdc1394-22-dev
gem install hornetseye-1394
sudo aptitude install -y libavformat-dev libswscale-dev
gem install hornetseye-ffmpeg
gem install hornetseye-narray
gem install narray

opencv problem

tried gem install opencv which gave this output:

i have dealt with opencv before, so i knew there was something with a name like "libcv" that i probably needed. aptitude search libcv turned up what i was looking for. next this:
sudo aptitude install -y libcv-dev libcv2.1 libcvaux-dev libcvaux2.1

still no opencv gem

another try at gem install opencv gave this:

needs some highgui dev package i think. google search for the fail line yielded nothing, but i had more luck with aptitude search highgui|grep dev. this gave the package name which i installed via sudo aptitude install -y libhighgui-dev

still still no opencv gem

even after installing that stuff i get the following behavior

so i'm gonna go to sleep now and try to finish tomorrow. i'll probably just have to give a flag of what directory to include for opencv junk. (the bulk of this post was written a day before i posted it.)

Thursday, February 3, 2011

creating a gem

this whole post is useless but i already wrote it so i'm posting


this video goes over everything in this post, except for conventional directory and file layout and the bin/ directory. but i didn't find it until i was about to hit publish. oh wells.

scattered notes


it's been difficult to find a tutorial on building a gem. it seems as though many ways have come and gone, and not gone. bundler can create gems. gem can create gems if you set up the files correctly. jeweler. new gem. hoe. echoe... well bundler gem some_gem_name creates a skeleton project for you and makes it into a git repo for you so you can start off clean. that's right, it creates a skeleton and makes it a git repo. awesome. and it uses git to specify which files are included in the gem. check out some_gem_name/some_gem_name.gemspec after running that command. you'll see something like:
s.files         = `git ls-files`.split("\n")
s.test_files    = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables   =
`git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }

so it makes sense that bundler starts off the project under git control. this also forces me to think about what exactly is and isn't in git.

gem structure conventions


from reading through actionmailer and some other gems, i've found that the basic structure is to mirror ruby class and module nesting th directory structure. after running bundle gem some_gem_name a new directory called some_gem_name is created in the current directory. under that is Gemfile, some_gem_name.gemspec, lib/ some other stuff. under lib/ is some_gem_name/ and some_gem_name.rb. in some_gem_name.rb is a skeleton with a module named SomeGemName! i guess bundler just uses the convention of taking out underscores and capitalizing the next letter, and capitilizing the first letter too. so that's cool.

so now we're in lib/some_gem_name/


in lib/some_gem_name/ is a file named version.rb. in that is simply:
module SomeGemName
VERSION = "0.0.0"
end

based on what i've read in actionmailer and thor, this is also where the meat goes. the guts of the code that make the gem do what it does. every file that does something important and lib like should go in here. and it should begin with some requires, and all the code should be between a [module|class] SomeGemName and an end. in addition, any directory under this one (for example lib/some_gem_name/foo_bar) should be the name of a module or class, with the first capital letter made lower, and every following capital made lower and preceded by an underscore. so the directory foo_bar corresponds to the class or module FooBar. furthermore, the nesting of those classes and modules in ruby should reflect the nesting of the directories on the filesystem. for example lib/some_gem_name/foo_bar/ should contain files that begin with some requires, followed by opening the class|module SomeGemName and then opening the class|module FooBar.
for example, inside lib/some_gem_name/foo_bar/foo_bar.rb, you would find something like:
require 'nokogiri'

module SomeGemName
class FooBar
def baz directance
fronlum = turboencabulate directance
fronlum.dipits
end
end
end

another convention seems to be having a name.rb as a sibling to every lib/**/name/. so there's a some_gem_name.rb corresponding to lib/some_gem_name/ and located at lib/some_gem_name.rb. another example, there should be a foo_bar.rb for lib/some_gem_name/foo_bar/ located at lib/some_gem_name/foo_bar.rb

bin/


there's also the option of creating a directory bin/ as a sibling to lib/. this is what bundler does. it looks like the convention is to use a file with no extension. that's how bundler creates the bundle command. so that's cool. within these files, you can just require 'some_gem_name' and use the stuff in your gem libs. the context is already set up so your some_gem_name

rake


right after running bundle gem some_gem_name && cd some_gem_name you can do rake -T to see a list that looks like this:
rake build    # Build template_validator-0.0.4.gem into the pkg directory
rake install  # Build and install template_validator-0.0.4.gem into system ...
rake release  # Create tag v0.0.4 and build and push template_validator-0.0...

so after writing the code into the locations described above, you can run rake build && rake install && irb -r some_gem_name to test out the gem you just created! so that's awesome.

actionmailer has a neat trick

to turn some code i wrote into a gem, i decided to read through other gems for examples of how to do it. while reading through the actionmailer gem installed with rails 3.0.3, i found this /home/ozzloy/.rvm/gems/ruby-1.9.2-p136@rails3tutorial/gems/actionmailer-3.0.3/lib/rails/generators/mailer/templates/mailer.rb:

class <%= class_name %> < ActionMailer::Base
default :from => "from@example.com"
<% for action in actions -%>

# Subject can be set in your I18n file at config/locales/en.yml
# with the following lookup:
#
# en.<%= file_path.gsub("/",".") %>.<%= action %>.subject
#
def <%= action %>
@greeting = "Hi"

mail :to => "to@example.org"
end
<% end -%>
end

so that's cool! it's using ruby to generate ruby code. metaprogramming, but not by manipulating classes and modules directly. instead generating the source code to create modules and classes, which i presume gets printed to a file with scaffolding. and probably also eval'd so as to keep DRY. anyways, neat.

Saturday, January 29, 2011

heroku not working with rvm on ubuntu

turns out when rvm installs ruby 1.9.2 on ubuntu, it will keep compiling even if some libraries aren't there. so if you don't have ssl libraries, it will compile ruby, but you just won't get to require 'net/https'. which is cool. i prefer this behavior. but it leads to some head scratching when later on, trying to install and use heroku keys:add, you get messages like the following:
no such file to load -- net/https. Try running apt-get install libopenssl-ruby
(See full trace by running task with --trace)

wtf? so ok, sudo aptitude install -y libopenssl-ruby and try again.

but that same message comes up! i tried other stuff, like rvm package install openssl and still got the same error message. uninstalled the gemset and reinstalled. still no dice. uninstalled rvm completely rvm implode and reinstalled bash < <( curl http://rvm.beginrescueend.com/releases/rvm-install-head ), and that did the trick. in retrospect, all i probably needed to do was recompile 1.9.2. and even then, i probably just needed to recompile the openssl part with the libopenssl-ruby library installed on my system.

in short


so in short, what i needed to do was:

sudo aptitude install -y libopenssl-ruby{,1.9.1}
rvm implode
bash < <( curl http://rvm.beginrescueend.com/releases/rvm-install-head )
gem install rails
gem install heroku
heroku keys:add

and then continue with the rails tutorial heroku part

related posts


here's some posts i found while troubleshooting just now:

Tuesday, November 30, 2010

rexml notes

REXML::Document.write is deprecated


rexml printing can be done with something like:
#!/usr/bin/env ruby
require 'rexml/document'
include REXML

doc = Document.new
doc << Element.new('root')
doc.elements['root'] << Element.new('child')

output = ''
doc.write output
puts output
#<root><child/></root>

output, indent = '', 1
doc.write output, indent
puts "with indent:"
puts output
=begin
with indent:
<root>
 <child/>
</root>
=end


new hotness


but that's deprecated. so use REXML::Formatters instead.

#!/usr/bin/env ruby
require 'rexml/document'
include REXML
doc = Document.new
doc << Element.new('root')
doc.elements['root'] << Element.new('child')

output, indent = '', 1
Formatters::Pretty.new(indent).write doc, output
puts output
=begin
<root>
 <child/>
</root>
=end


there are 2 other formatters availabe: default, and transitive. transitive does its best to preserve content nodes, including whitespace, but it will insert whitespace in non-content areas to improve formatting. so between attributes, tagnames, but not in text nodes.

more pretty print, please


pretty print also has a width, and a compact. compact will fit nodes with only text children onto 1 line if it can be done smaller than the width. large sections of text are always wrapped at 80 chars and indented 1 level further than their parent.
#!/usr/bin/env ruby
require 'rexml/document'
include REXML

doc = Document.new
doc << Element.new('root')
child = Element.new('child')
child << Text.new(<<-EOT)
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
EOT
small = Element.new('small')
small << Text.new(' little
text ')
doc.elements['root'] << child
doc.elements['root'] << small


output, indent = '', 20
pretty = Formatters::Pretty.new(indent)
pretty.width = 75
pretty.compact = true
pretty.write doc, output
puts output
=begin
<root>
<child>
Lorem ipsum dolor sit amet, consectetur
adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris
nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit
in voluptate velit esse cillum dolore eu
fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in
culpa qui officia deserunt mollit anim
id est laborum.
</child>
<small> little text </small>
</root>
=end


side note


i used this line for printing the above stuff escaping the characters, but preserving the whitespace:
File.open(__FILE__){ |f| puts Text.new(f.readlines.join, true) }

adding children on child creation


some child elements can have their parent node set on creation. works for Document, and Element nodes, but this doesn't work for text nodes, as far as i can tell.
#!/usr/bin/env ruby
require 'rexml/document'
include REXML

doc = Document.new
root = Element.new('root', doc)
child = Element.new('child', root)
Text.new('Lorem ipsum', child) #doesn't work, why?
small = Element.new('small', root)
little = Text.new(' little
text ')
small << little # adding text nodes like this works


output, indent = '', 20
pretty = Formatters::Pretty.new(indent)
pretty.width = 75
pretty.compact = true
pretty.write doc, output
puts output
=begin
<root>
<child/>
<small> little text </small>
</root>
=end

Monday, July 26, 2010

ruby Array#uniq uses eql? and hash

this one kept me busy for 20 minutes


if you create an array of objects and wish to call uniq on that array, the objects of the array must supply both the eql? and hash methods. the hash method must return an integer; it's not enough that the return value be constant, it must be a Fixnum.

an example


here's some code to demonstrate that you need both to be defined.

class Foo
attr_reader :s
def initialize s
@s = s
end
def inspect
"#{self.class}: @s=#{@s.inspect}"
end
alias :to_s :inspect
end
foo_array = ["a","b","b"].map{|e|Foo.new e}
puts "initially:"
puts " #{foo_array.inspect}"
puts " #{foo_array.uniq.join ', '}"
#initially:
# [Foo: @s="a", Foo: @s="b", Foo: @s="b"]
# Foo: @s="a", Foo: @s="b", Foo: @s="b"

class Foo
alias :old_hash :hash
def hash
@s.hash
end
end
puts "with hash defined:"
puts " #{foo_array.inspect}"
puts " #{foo_array.uniq.join ', '}"
#with hash defined:
# [Foo: @s="a", Foo: @s="b", Foo: @s="b"]
# Foo: @s="a", Foo: @s="b", Foo: @s="b"

class Foo
undef hash
alias :hash :old_hash
def eql? o
@s == o.s
end
end
puts "with eql? defined:"
puts " #{foo_array.inspect}"
puts " #{foo_array.uniq.join ', '}"
#with eql? defined:
# [Foo: @s="a", Foo: @s="b", Foo: @s="b"]
# Foo: @s="a", Foo: @s="b", Foo: @s="b"

class Foo
def hash
@s.hash
end
end
puts "with eql? and hash defined:"
puts " #{foo_array.inspect}"
puts " #{foo_array.uniq.join ', '}"
#with eql? and hash defined:
# [Foo: @s="a", Foo: @s="b", Foo: @s="b"]
# Foo: @s="a", Foo: @s="b"

=begin
# ruby asdf.rb
initially:
[Foo: @s="a", Foo: @s="b", Foo: @s="b"]
Foo: @s="a", Foo: @s="b", Foo: @s="b"
with hash defined:
[Foo: @s="a", Foo: @s="b", Foo: @s="b"]
Foo: @s="a", Foo: @s="b", Foo: @s="b"
with eql? defined:
[Foo: @s="a", Foo: @s="b", Foo: @s="b"]
Foo: @s="a", Foo: @s="b", Foo: @s="b"
with eql? and hash defined:
[Foo: @s="a", Foo: @s="b", Foo: @s="b"]
Foo: @s="a", Foo: @s="b"
=end

references


this forum finally led me to the idea of overriding hash and eql?. but it also says that the only requirement for hash is that it be constant for a given state of an object. well it also needs to be a number, it turns out. otherwise you get something like this:

asdf.rb:26:in `uniq': can't convert String into Integer (TypeError)
from asdf.rb:26:in `
'

infuriating. i had no idea what integer it was talking about. i see no integer! AAUGH! so it turns out that someone in a thread on the internet wasn't completely correct.

Friday, February 5, 2010

slightly better kludge for suppressing ruby soap warnings

code i ended up with, followed by a description of the journey:

#monkeypatch kludge to get Parser to suppress "ignored element" warnings
#generated when mumboe-soap4r consumes wsdl that asp.net serves
#TODO: find a cleaner way to do this
class WSDL::Parser
old_initialize = instance_method(:initialize)
define_method(:initialize) do |*args, &block|
old_initialize.bind(self).call(*args, &block)

#set up QNames to ignore
names = ["binding", "operation", "body", "header", "address"]
namespace = "http://schemas.xmlsoap.org/wsdl/soap12/"
ignored = names.inject({}) do |ignored, name|
elename = XSD::QName.new(namespace, name)
ignored.update(elename => elename)
end

instance_variable_set(:@ignored, ignored)
end
end

how i got there


yesterday i implemented a kludge to suppress these warnings, but it was a bit broad. it would suppress everything printed to stderr during decode_tag. i refined that method to get to the code above. to make yesterday's kludge, i had to read some of the code in /var/lib/gems/1.9.0/gems/mumboe-soap4r-1.5.8.3/lib/wsdl/parser.rb. i noticed the use of @ignored to prevent duplicate warnings. i figured i could populate it with the things i don't care about before doing any wsdl consumption. turns out that worked.

what warnings to suppress


so i needed to print out the contents of @ignored. at first, i tried monkeypatching decode_tag to print out stuff as it was added to @ignored but that resulted in many duplicates. ironically, avoiding this duplication is exactly the reason for having @ignored. instead i went to the place where decode_tag was first called and monkeypatched that method (start_element).

deeper


i found that @ignored was populated with XSD::QNames. so i went to .../lib/xsd/qname.rb to find out how to create them and how they were compared. QName creation requires a namespace and a name. so i needed to have each key and value in @ignore print its namespace and name. fortunately these were readable attributes, so i just had to modify start_element in wsdl/parser.rb

back to wsdl/parser.rb


so i landed on this monkeypatch, which is the slickness:

class WSDL::Parser
def parse(string_or_readable)
@parsestack = []
@lastnode = nil
@textbuf = ''
@parser.do_parse(string_or_readable)
puts
puts "ignored = {"
@ignored.each do |key, value|
puts "XSD::QName.new(\"#{key.namespace}\", \"#{key.name}\") =>"
puts "XSD::QName.new(\"#{value.namespace}\", \"#{value.name}\"),"
end
puts "}"
@lastnode
end
end

that's right, it prints out the information i need formatted as ruby code so i just copy-pasta'd the output back into my code and massaged it a little.

kinda sorta almost


this result was almost what i wanted. here's the code:

class WSDL::Parser
old_initialize = instance_method(:initialize)
define_method(:initialize) do |*args, &block|
old_initialize.bind(self).call(*args, &block)
ignored = {
XSD::QName.new("http://schemas.xmlsoap.org/wsdl/soap12/", "binding") =>
XSD::QName.new("http://schemas.xmlsoap.org/wsdl/soap12/", "binding"),
XSD::QName.new("http://schemas.xmlsoap.org/wsdl/soap12/", "operation") =>
XSD::QName.new("http://schemas.xmlsoap.org/wsdl/soap12/", "operation"),
XSD::QName.new("http://schemas.xmlsoap.org/wsdl/soap12/", "body") =>
XSD::QName.new("http://schemas.xmlsoap.org/wsdl/soap12/", "body"),
XSD::QName.new("http://schemas.xmlsoap.org/wsdl/soap12/", "header") =>
XSD::QName.new("http://schemas.xmlsoap.org/wsdl/soap12/", "header"),
XSD::QName.new("http://schemas.xmlsoap.org/wsdl/soap12/", "address") =>
XSD::QName.new("http://schemas.xmlsoap.org/wsdl/soap12/", "address"),
}
instance_variable_set(:@ignored, ignored)
end
end

this was nearly good enough for me to stop. it suppressed exactly what i knew about. nothing more, nothing less. but that's a lot of text. and a lot of it is repepetetetivive. and every QName is created twice, so technically it wasn't populating @ignored in exactly the same way as decode_tag does. and what if the namespace needs changing, or i want to add another name? i felt this would be annoying to maintain.

another step


so i used a variable to store the namespace and used a variable to store each QName.
here's that code:

class WSDL::Parser
old_initialize = instance_method(:initialize)
define_method(:initialize) do |*args, &block|
old_initialize.bind(self).call(*args, &block)
namespace = "http://schemas.xmlsoap.org/wsdl/soap12/"
binding = XSD::QName.new(namespace, "binding")
operation = XSD::QName.new(namespace, "operation")
body = XSD::QName.new(namespace, "body")
header = XSD::QName.new(namespace, "header")
address = XSD::QName.new(namespace, "address")
ignored = {
binding => binding,
operation => operation,
body => body,
header => header,
address => address,
}
instance_variable_set(:@ignored, ignored)
end
end

all right. better. but ... augh, i can't let it be that way. i mean, come on! for every ignored thing, the name of the ignored thing shows up 4 times, on 2 different lines that aren't right next to each other. still not DRY enough. i figured i could create an array with symbols and do something with that. turns out that 3 of the 4 times a name showed up, it was just a temporary variable and the true essence could be summed up more generically so that any particular name was only given once! so i messed with Enumerable#each and finally landed on a workable solution using Enumberable#inject.

final code again (so you don't have to scroll up):



#monkeypatch kludge to get Parser to suppress "ignored element" warnings
#generated when mumboe-soap4r consumes wsdl that asp.net serves
#TODO: find a cleaner way to do this
class WSDL::Parser
old_initialize = instance_method(:initialize)
define_method(:initialize) do |*args, &block|
old_initialize.bind(self).call(*args, &block)

#set up QNames to ignore
names = ["binding", "operation", "body", "header", "address"]
namespace = "http://schemas.xmlsoap.org/wsdl/soap12/"
ignored = names.inject({}) do |ignored, name|
elename = XSD::QName.new(namespace, name)
ignored.update(elename => elename)
end

instance_variable_set(:@ignored, ignored)
end
end

now when someone wants to add a new ignored name, they just add it to the list of names that get ignored! one place! <comma> <space> <quotation mark> <name> <quotation mark>. the rest of the work is done generically, automatically. and i think reading this is easier than reading the intermediate steps. there's less to read. less dense. easier to update. a good kludge.
so i'm glad that's done. ... or is it?

it's still a kludge


ultimately, this is neat and all, but it's still a kludge. i need to figure out why these warnings are generated at all. i don't want to have to read a wsdl, or read more code involved in the process of parsing a wsdl. a brief look tells me it must be that parent.parse_element(elename) returns nil in some case. i don't know what type parent is and i don't feel like searching any further right now.

Thursday, February 4, 2010

kludge: suppress mumboe-soap4r warnings

first the code, then the explanation:

#monkeypatch kludge to get Parser to suppress "ignored element" warnings
#generated when mumboe-soap4r consumes wsdl that asp.net serves
#TODO: find a cleaner way to do this
require 'stringio'
class WSDL::Parser
private
old_decode_tag = instance_method(:decode_tag)
ignored_string = StringIO.new
define_method(:decode_tag) do |*args, &block|
old_stderr, $stderr = $stderr, ignored_string
result = old_decode_tag.bind(self).call(*args, &block)
$stderr = old_stderr
result
end
end

situation


recently i've been dealing with soap. T_T. but i'm getting paid. ^_^. i'm writing the client in ruby 1.9 using mumboe-soap4r lib (gem1.9 install -r mumboe-soap4r). asp.net serves up the web services. the wsdl that asp.net serves has elements that the ruby lib ignores. mumboe-soap4r generates warnings printed to stderr.
the warnings (modified to be more generic):

ignored element: {http://schemas.xmlsoap.org/wsdl/soap12/}binding : #<WSDL::Binding:0xd2c490 {http://example.com/ExampleServices}ExampleSoap12>
ignored element: {http://schemas.xmlsoap.org/wsdl/soap12/}operation : #<WSDL::OperationBinding:0xd21a54 CheckLogOnCredentials>
ignored element: {http://schemas.xmlsoap.org/wsdl/soap12/}body : #<WSDL::Param:0xd20a78 >
ignored element: {http://schemas.xmlsoap.org/wsdl/soap12/}header : #<WSDL::Param:0xd20a78 >
ignored element: {http://schemas.xmlsoap.org/wsdl/soap12/}address : #<WSDL::Port:0x1083bfc {http://example.com/ExampleServices}ExampleSoap12>

motivation


this was printed out to stderr every time the client grabbed the wsdl and parsed it. reading unit test results was quite annoying. and running the client was annoying. i could just redirect stderr to /dev/null, but then i wouldn't get any errors at all. this code diagnoses problems and uses stderr to report those problems. so i need something more precise.

solution


so instead i redirect stderr but only for the duration of the method that actually generates warnings. the file /var/lib/gems/1.9.0/gems/mumboe-soap4r-1.5.8.3/lib/wsdl/xmlSchema/parser.rb (on ubuntu 9.10) defines the decode_tag method. i found it like this:

% gem1.9 environment|grep INSTALLATION
- INSTALLATION DIRECTORY: /var/lib/gems/1.9.0
% cd /var/lib/gems/1.9.0/
% ls
% cd mumboe-soap4r-1.5.8.3/lib
% grep -r "ignored element" *
wsdl/parser.rb
wsdl/xmlSchema/parser.rb

then i went back to a blog post i read earlier: jay fields alias method alternative. i also noticed there a link to another post by martin on method replacing. then i did a bit of trial and error to get it working for me in this case, where the class is defined in a module. once i was able to replace the method with my code, written in my file, i just needed to write code that would suppress stderr, call the original method, then resurrect stderr. temporarily redirecting stdout (or stderr) is common enough that someone had written nearly exactly what i needed. i didn't need to search for long.

Wednesday, January 27, 2010

ruby 1.9 libs, openssl

yet another problem solved:

ledZeppelin% ./minimal.rb
/usr/lib/ruby/1.9.0/net/smtp.rb:197:in `default_ssl_context': uninitialized constant Net::SMTP::OpenSSL (NameError)
from /usr/lib/ruby/1.9.0/net/smtp.rb:342:in `enable_starttls'
from ./minimal.rb:24:in `_send_email'
from ./minimal.rb:33:in `
'
ledZeppelin% #futz around with gem1.9 looking for the obvious ssl package
ledZeppelin% aptitude search ssl|grep -i ruby
p libopenssl-ruby - OpenSSL interface for Ruby
i A libopenssl-ruby1.8 - OpenSSL interface for Ruby 1.8
p libopenssl-ruby1.9 - OpenSSL interface for Ruby 1.9
p libopenssl-ruby1.9.1 - OpenSSL interface for Ruby 1.9.1
ledZeppelin% sudo aptitude install libopenssl-ruby1.9
[sudo] password for danny:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
The following NEW packages will be installed:
libopenssl-ruby1.9
0 packages upgraded, 1 newly installed, 0 to remove and 15 not upgraded.
Need to get 133kB of archives. After unpacking 979kB will be used.
Writing extended state information... Done
Get:1 http://us.archive.ubuntu.com karmic/universe libopenssl-ruby1.9 1.9.0.5-1ubuntu1 [133kB]
Fetched 133kB in 1s (121kB/s)
Selecting previously deselected package libopenssl-ruby1.9.
(Reading database ... 212364 files and directories currently installed.)
Unpacking libopenssl-ruby1.9 (from .../libopenssl-ruby1.9_1.9.0.5-1ubuntu1_amd64.deb) ...
Setting up libopenssl-ruby1.9 (1.9.0.5-1ubuntu1) ...
Reading package lists... Done
Building dependency tree
Reading state information... Done
Reading extended state information
Initializing package states... Done
Writing extended state information... Done
ledZeppelin% uname -a
Linux ledZeppelin 2.6.31-17-generic #54-Ubuntu SMP Thu Dec 10 17:01:44 UTC 2009 x86_64 GNU/Linux
ledZeppelin% lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 9.10
Release: 9.10
Codename: karmic
ledZeppelin% ./minimal.rb
ledZeppelin% #email in my inbox, yay


and that was it

be careful with ruby include

turns out the problem i've been having over the last few days has been that i included some libs in the top level of a ruby file. so the module's definition of "read" overrode the kernel's version. as you might suspect, changing ruby's idea of "read" around leads to errors. in my case, the first code to hit this was inside a soap library, which called an http library. so i thought the problem might be in there. i spent yesterday and today tracking that error down. i did other things during that time, but still that was lots of time.

i tracked it down by creating a minimal test case for the soap portion, iprofiletools.rb, creating a class out of it and having a small driver at the end of the class definition file: if $0 == __FILE__ then driver_code end.
when that worked, but using the class in the project still yielded errors, i knew it wasn't the soap code that was bad. i suspected global variables or constants set in the module might be messing with some setting used somewhere down the line.
so i tried putting in all the includes from vue_monitor.rb to the top of iprofiletools.rb.
this reproduced the errors i saw when running vue_monitor.rb. since i didn't actually need any of those "require"s and "include"s, i started removing them and rerunning iprofiletools until i had a minimal set that created the error. that led me to SimpleCommons
i looked in SimpleCommons for globals and constants and found nothing obvious. so i started commenting out large portions and rerunning iprofiletools. eventually i narrowed it down to the read function.
that's when i realized that i was "include"ing SimpleCommons at the top level. all i needed to do was include it within the class, instead of at the top level, directly into Kernel.
that's a better model of what i want anyways. i want the stuff in SimpleCommons to be a part of the Vue_Monitor class, not a part of Kernel.

i'm not sure how this problem didn't come up earlier. git bisect would have been a better approach to this. i could have seen the diff that started this all. but the problem only appeared on one machine and not on my laptop. so i initially started with the suspicion that the installed library was the culprit. i'm still not sure why errors only produced on one machine and not the other.

anywho. i've fixed it. i understand part of what was wrong. i know now to be careful with includes.

Thursday, October 15, 2009

send email through gmail via ruby 1.8.7 and later

this took me some searching and eventually talking to drbrain on freenode #ruby-lang. i then found that drbrain wrote the ruby gem smtp_tls which makes this work for 1.8.6 and possibly earlier. so that's kinda cool.

here's the minimal ruby example. put this in a file

require 'net/smtp'

host = 'smtp.gmail.com'
port = 587
relay_domain = 'example.com' #doesn't matter
send_account = 'gmail_account' # i.e. "example" from "example@google.com"
recv_account = 'receiver_account' #i.e. "acct" from "acct@example.com"
pw = "password"
auth_type = :login #:cram_md5 doesn't work

from ="#{send_account}@gmail.com"
to = "#{recv_account}@example.com"
subject = "subject line goodness"
body = "look, it's an email body!"

msg = <<END_OF_MESSAGE
From: #{from}
To: #{to}
Subject: #{subject}

#{body}
END_OF_MESSAGE

smtp = Net::SMTP.new host, port
smtp.enable_starttls
smtp.start(relay_domain, send_account, pw, auth_type) do |server|
server.send_message(msg, from, to)
end

Where am I?