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.

Wednesday, February 2, 2011

ruby 1.9 gem 1.5 bundler 1.0.9 problem fixed

bundler 1.0.10 fixed whatever problem it had with gem 1.5. just have bundler at or above version 1.0.10 and gem 1.5, or bundler 1.0.9 or below with gem 1.4. and all of this seems to only have been an issue on ruby 1.9.*. i saw no reports of problems on ruby 1.8.?

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.

Monday, April 5, 2010

gitweb serving gitosis repos via apache2 (on ubuntu karmic)

set up gitosis

install packages


sudo aptitude install gitweb apache2

configure gitweb


modify /etc/gitweb.conf:

# path to git projects (.git)
#$projectroot = "/var/cache/git";
$projectroot = "/srv/gitosis/repositories";

# directory to use for temp files
$git_temp = "/tmp";

# target of the home link on top of all pages
#$home_link = $my_uri || "/";

# html text to include at home page
$home_text = "indextext.html";

# file with project list; by default, simply scan the projectroot dir.
#$projects_list = $projectroot;
$projects_list = "/srv/gitosis/gitosis/projects.list";

# stylesheet to use
#$stylesheet = "/gitweb.css";
$stylesheet = "/git/gitweb.css";

# logo to use
#$logo = "/git-logo.png";
$logo = "/git/git-logo.png";

# the 'favicon'
#$favicon = "/git-favicon.png";
$favicon = "/git/git-favicon.png";

configure apache2


create /etc/apache2/conf.d/git with this content:

<Directory /var/www/git>
Allow from all
AllowOverride all
Order allow,deny
Options ExecCGI
<Files gitweb.cgi>
SetHandler cgi-script
</Files>
</Directory>
DirectoryIndex gitweb.cgi
SetEnv GITWEB_CONFIG /etc/gitweb.conf

make files visible to apache2

sudo mkdir /var/www/git
sudo cp /usr/share/gitweb/* /var/www/git
sudo cp /usr/lib/cgi-bin/gitweb.cgi /var/www/git
sudo /etc/init.d/apache2 reload
chmod 0755 /srv/gitosis/repositories/test_repo.git

configure gitosis



git clone gitosis@localhost:gitosis-admin.git
cd gitosis-admin

modify gitosis.conf, add the following:

[repo test_repo]
gitweb = yes
description = one line test repo description
owner = first_name last_name

save the configuration and push it back to gitosis

git add gitosis.conf
git ci -m "publishing test_repo via gitweb"
git push origin master

try it out


open http://localhost/git and see test_repo.git in column titled "Project"

references


Where am I?